Question

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

Solution 1 -- Inorder Traversal

Again, we use the feature of inorder traversal of BST. But this solution is not best for follow up. Time complexity O(n), n is the number of nodes.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
TreeNode current = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (current != null || !stack.empty()) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
TreeNode tmp = stack.pop();
k--;
if (k == 0) {
return tmp.val;
}
current = tmp.right;
}
}
return -1;
}
}

Solution 2 -- Augmented Tree

The idea is to maintain rank of each node. We can keep track of elements in a subtree of any node while building the tree. Since we need K-th smallest element, we can maintain number of elements of left subtree in every node.

Assume that the root is having N nodes in its left subtree. If K = N + 1, root is K-th node. If K < N, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > N + 1, we continue our search in the right subtree for the (K – N – 1)-th smallest element. Note that we need the count of elements in left subtree only.

Time complexity: O(h) where h is height of tree.

(referrence: GeeksforGeeks)

Here, we construct tree in a way that is taught during Algorithm class.

"size" is an attribute which indicates number of nodes in sub-tree rooted in that node.

Time complexity: constructing tree O(n), find Kth smallest number O(h).

start:
if K = root.leftElement + 1
root node is the K th node.
goto stop
else if K > root.leftElements
K = K - (root.leftElements + 1)
root = root.right
goto start
else
root = root.left
goto srart stop
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class ImprovedTreeNode {
int val;
int size; // number of nodes in the subtree that rooted in this node
ImprovedTreeNode left;
ImprovedTreeNode right;
public ImprovedTreeNode(int value) {val = value;}
} public class Solution { // Construct ImprovedTree recursively
public ImprovedTreeNode createAugmentedBST(TreeNode root) {
if (root == null)
return null;
ImprovedTreeNode newHead = new ImprovedTreeNode(root.val);
ImprovedTreeNode left = createAugmentedBST(root.left);
ImprovedTreeNode right = createAugmentedBST(root.right);
newHead.size = 1;
if (left != null)
newHead.size += left.size;
if (right != null)
newHead.size += right.size;
newHead.left = left;
newHead.right = right;
return newHead;
} public int findKthSmallest(ImprovedTreeNode root, int k) {
if (root == null)
return -1;
ImprovedTreeNode tmp = root;
int leftSize = 0;
if (tmp.left != null)
leftSize = tmp.left.size;
if (leftSize + 1 == k)
return root.val;
else if (leftSize + 1 > k)
return findKthSmallest(root.left, k);
else
return findKthSmallest(root.right, k - leftSize - 1);
} public int kthSmallest(TreeNode root, int k) {
if (root == null)
return -1;
ImprovedTreeNode newRoot = createAugmentedBST(root);
return findKthSmallest(newRoot, k);
}
}

Kth Smallest Element in a BST 解答的更多相关文章

  1. 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)

    Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the k ...

  2. [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素

    题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...

  3. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...

  4. 【刷题-LeetCode】230. Kth Smallest Element in a BST

    Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the k ...

  5. leetCode(46):Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  6. [LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  7. Leetcode Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  8. Leetcode 230. Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  9. Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

随机推荐

  1. 10招搞定web设计风格指南

    From:http://www.ui.cn/detail/27579.html 今时今日,网站的创建正变得越来越复杂,而且一般都不是一个人就能干的了的.在创建网站过程中,我们需要保证设计前后一致,并符 ...

  2. win环境下mysql5.6.14的所有变量的默认值

    在windows mysql5.6.14 x64版本下my.ini如下: [mysqld] port  = 3306 socket  = /tmp/mysql.sock basedir=D:/wamp ...

  3. python学习之路-11 多线程、多进程、协程

    python内置队列模块 queue queue的四种队列 q = queue.Queue() # 先进先出队列 q = queue.LifoQueue() # 后进先出队列 q = queue.Pr ...

  4. Arithmetic Sequence(dp)

    Arithmetic Sequence Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 51  Solved: 19[Submit][Status][We ...

  5. 21. DNS 配置和端口检测

    一.将本机的 DNS 配置为 8.8.8.8 ,用 nslookup (还可以使用 host.dig)验证 # 修改配置文件     # vim /etc/resolv.conf # 在文件的最后加入 ...

  6. Android ---------- 清单文件中Activity常规设置

    <activity android:name="xxxxx" android:alwaysRetainTaskState="true" android:c ...

  7. Cisco cmd命令(三)动态路由协议

    路由选择协议:1.矢量距离协议 2.链路状态协议 RIP路由选择协议:1.使用矢量距离协议 2.RIPv1只能使用有类路由 3.RIPv2可以使用无类路由 路由更新定时器:用于将路由器本身完整的路由选 ...

  8. vs中动态DLL与静态LIB工程中加入版本信息的方法

    说明:本文仅针对刚接触VS不久的新手们(包括ME),提供的一点小Tips,同时也是小生的首篇Blog文章,请大伙多多担待O(∩_∩)O哈! 步骤1 - 在工程中右键添加新建项 步骤2 - 选择创建RC ...

  9. 一、Autofac入门

    想要将autofac集成到你的应用程序中需要经过如下步骤: 1.使用控制翻转(IoC)的思想架构你的应用程序: 2.添加autofac引用: 3.在应用程序入口...(At application s ...

  10. bzoj 2049 Cave 洞穴勘测(LCT)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud 动态树入门题,不需要维护任何信息. 我用的是splay,下标实现的lct. #in ...