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 ...
随机推荐
- 通过Excel来集中管理资源文件
在支持双语或多语种项目中,常常需要编辑多个文件来添加资源项,感觉比较繁琐,所以想做一个可以集中管理资源文件的工具.借助Excel,使用Excel来记录,并且通过Excel可以进行分页分模块来规划 ...
- DB2 中日期 比较
在DB2中的Date 一共识别三种格式,最常见的是这样 '2013-12-12' 对,你没看错,DB2认为这样的字符串就是Date数据 然后我们可以利用函数这样寻找日期区间 select * from ...
- qt Graphics View Framework(非重点)
Graphics View 提供了一种接口,用于管理大量自定义的 2D 图形元素,并与之进行交互:还提供了用于将这些元素进行可视化显示的观察组件,并支持缩放和旋转. 说明;Graphics View ...
- 删除list中指定值的元素
public class ListRemoveAll { public static void main(String[] args) { // TODO Auto-generated method ...
- [Immutable,js] Immutable.Record() as data models
The Immutable.js Record() allows you to model your immutable data much like you would model data wit ...
- BackgroundWorker 后台进程控制窗体label、richtextbook内容刷新
昨天写了一个从文章中提取关键词的程序,写完处理的逻辑后又花了好几个小时在用户友好性上.加了几个progressBar,有显示总进度的.有显示分布进度的..因为程序要跑好几个小时才能执行好,只加个总进度 ...
- mysql忘记密码时如何修改root用户密码
1.关闭正在运行的MySQL服务. 2.打开DOS窗口,转到mysql\bin目录. 3. 输入mysqld --skip-grant-tables 回车.--skip-grant-tables 的意 ...
- asp.net缓存(三)
Asp.net应用程序数据缓存 System.Web.Caching 命名空间提供用于缓存服务器上常用数据的类.此命名空间包括 Cache 类,该类是一个字典,您可以在其中存储任意数据对象,如哈希表和 ...
- javascirpt IP验证
js IP 端口验证 function isPort(str) { var parten=/^(\d)+$/g; if(parten.test(str)&&parseI ...
- oracle 语句汇总
Oracle数据库常用sql语句 ORACLE 常用的SQL语法和数据对象 一.数据控制语句 (DML) 部分 1.INSERT (往数据表里插入记录的语句) INSERT INTO 表名(字段名1 ...