Kth Smallest Element in a BST 解答
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:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- 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 解答的更多相关文章
- 【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 ...
- [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素
题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...
- LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)
230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...
- 【刷题-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 ...
- 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 ...
- [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 ...
- 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 ...
- 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 ...
- Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...
随机推荐
- sae-v2ex 一个运行在SAE上的类似v2ex的轻型python论坛 - 技术讨论 - 云计算开发者社区 - Powered by Discuz!
sae-v2ex 一个运行在SAE上的类似v2ex的轻型python论坛 - 技术讨论 - 云计算开发者社区 - Powered by Discuz! sae-v2ex 一个运行在SAE上的类似v2e ...
- POJ 1742 Coins(多重背包) DP
参考:http://www.hankcs.com/program/cpp/poj-1742-coins.html 题意:给你n种面值的硬币,面值为a1...an,数量分别为c1...cn,求问,在这些 ...
- hdu 5288 OO’s Sequence(计数)
Problem Description OO has got a array A of size n ,defined a function f(l,r) represent the number o ...
- ubuntu apache2配置详解(含虚拟主机配置方法)
ubuntu apache2配置详解(含虚拟主机配置方法) 在Windows下,Apache的配置文件通常只有一个,就是httpd.conf.但我在Ubuntu Linux上用apt-get inst ...
- NET基础课-- 类型基础(NET之美)
1.类型:值类型 引用类型. 分类依据:类型在内存的分配方式.值类型在堆栈,引用类型在托管堆. 名词:栈--所有变量都会被分配在栈上,只不过值类型直接含有数据,引用类型含有一个指向托管堆对象的地址. ...
- Query获取值常用
Query获取Select选择的Text和Value:语法解释:1. $("#select_id").change(function(){//code...}); //为Sel ...
- SQL常用分页
top式 string sqltext = string.Format(" SELECT TOP {0} * FROM '表' WHERE ('字段' NOT IN (SELECT TOP ...
- jquery css3 手机菜单动画综合版
html <header> <a id="go-back" href="javascript:window.location.back(-1)" ...
- HBase配置&启动脚本分析
本文档基于hbase-0.96.1.1-cdh5.0.2,对HBase配置&启动脚本进行分析 date:2016/8/4 author:wangxl HBase配置&启动脚本分析 剔除 ...
- C++服务器设计(二):应用层I/O缓冲
数据完整性讨论 我们已经选择了I/O复用模型作为系统底层I/O模型.但是我们并没有具体解决读写问题,即在我们的Reactor模式中,我们怎么进行读写操作,才能保证对于每个连接的发送或接收的数据是完整的 ...