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.
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?
思路:inorder travel,实际考察的就是用stack来模拟inorder travel的过程,然后记录node个数就可以了。第k个就是所求。 time O(k); 对于follow up 问题:可以用maxheap就可以了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root == null) {
return -1;
}
Stack<TreeNode> stack = new Stack<>();
pushLeft(root, stack);
int count = 0;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
count++;
if(count == k) {
return node.val;
}
if(node.right != null) {
pushLeft(node.right, stack);
}
}
return -1;
}
private void pushLeft(TreeNode node, Stack<TreeNode> stack) {
while(node != null) {
stack.push(node);
node = node.left;
}
}
}