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?
这道题其实很好地利用BST的特点就好了,举个栗子:
2
/ \
1 3
我怎么找到第kth的?如果我能排序的话,是不是特别简单。所以我一眼就看出来了,这其实不就是中序遍历放进一个queue就好了么。。。
当然,这里要注意,queue和stack在java里不一样,stack可以直接new,而queue是一个interface,所以new的时候只能 new LinkedList()或者new ArrayDeque();
然后就是巧用queue做中序遍历:
package testAndfun;
import java.util.ArrayDeque;
import java.util.Queue;
public class KthSmallestEle {
Queue<Integer> queue = new ArrayDeque<Integer>();
public int kthSmallest(TreeNode root, int k){
foo(root);
while(k>1){
queue.poll();
k--;
}
return queue.poll();
}
public void foo(TreeNode root) {
if(root.left!=null){
foo(root.left);
queue.add(root.val);
if(root.right!=null){
foo(root.right);
}
}
else{
queue.add(root.val);
if(root.right!=null){
foo(root.right);
}
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}
}