230. Kth Smallest Element in a BST - jiejackyzhang/leetcode-note GitHub Wiki
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).
Tree类题目。 BST的特点是如果inorder traversal可以得到排序的结果。 因此采用这种思路,第k个即为所求。
##Approach 1: iterative
/**
* 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) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null) {
stack.push(node);
node = node.left;
}
while(!stack.empty()) {
node = stack.pop();
k--;
if(k == 0) return node.val;
node = node.right;
while(node != null) {
stack.push(node);
node = node.left;
}
}
return -1;
}
}##Binary Search 每次计算一下左子树的节点个数count,
- 如果k==count+1,则root即为所求;
- 如果k<=count,则在左子树中继续寻找kth smallest element;
- 如果k>count+1,则在右子树中继续寻找(k-count-1)th smallest element。
/**
* 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) {
int count = countNodes(root.left);
if(k <= count) {
return kthSmallest(root.left, k);
} else if(k > count + 1) {
return kthSmallest(root.right, k-count-1);
}
return root.val;
}
private int countNodes(TreeNode root) {
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}