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?
題意:從一個(gè)二叉搜索樹上找第k小元素。
followup:如果這個(gè)二叉樹經(jīng)常改變(增刪),然后又會經(jīng)常查第k小元素,該怎么優(yōu)化?
1、暴力的思路:把二叉搜索樹轉(zhuǎn)為一個(gè)有序數(shù)組,返回?cái)?shù)組第k-1個(gè)元素。要遍歷所有樹節(jié)點(diǎn),時(shí)間復(fù)雜度O(n);要用一個(gè)數(shù)組存儲,空間復(fù)雜度O(n)。
2、先找到最小元素,通過棧存儲父節(jié)點(diǎn),利用前序遍歷找到第k個(gè)。
public int kthSmallest(TreeNode root, int k) {
//1 bst轉(zhuǎn)為有序數(shù)組,返回第k個(gè),時(shí)間 O(n), 空間 O(n)
//2 先找到bst中最小的葉子節(jié)點(diǎn),然后遞歸向上搜索第k個(gè),父節(jié)點(diǎn)存儲在棧中
Stack<TreeNode> stack = new Stack<>();
TreeNode dummy = root;
while (dummy != null) {
stack.push(dummy);
dummy = dummy.left;
}
while (k > 1) {
TreeNode top = stack.pop();
dummy = top.right;
while (dummy != null) {
stack.push(dummy);
dummy = dummy.left;
}
k--;
}
return stack.peek().val;
}