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?
中序遍历把数存到一个list中,多次读取挺方便的,修改的话直接在list也能操作
public class Solution {
List<Integer> list;
public int kthSmallest(TreeNode root, int k) {
list = new ArrayList<>();
helper(root);
return list.get(k-1);
}
private void helper(TreeNode root){
if(root==null) return;
helper(root.left);
list.add(root.val);
helper(root.right);
}
}
不过大概题目不是这个意思吧。。。那还是在遍历的时候统计一下数目好了