一、问题描述
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).
二、问题分析
结合BST的结构,可以采用中序遍历的方式,并且通过一个count值来统计遍历的个数,时间复杂度O(logn)。
三、Java AC代码
public int kthSmallest(TreeNode root, int k) {
List<Integer> list = new ArrayList<Integer>();
inOrderTraverse(root, list, k);
return list.get(k-1);
}
public void inOrderTraverse(TreeNode root, List<Integer> list, int k){
if (root == null || k<=0) {
return ;
}
inOrderTraverse(root.left, list, k--);
list.add(root.val);
inOrderTraverse(root.right, list, k--);
}