原题:
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?
解决方法:
采用dfs的方法,先从左子树找,然后比较自己,然后是右子树,其实就是一个中序遍历的过程。
代码:
int dfs(TreeNode* root, int& k){
if (!root)
return 0;
int x = dfs(root->left, k);
return k == 0 ? x : (--k == 0 ? root->val : (dfs(root->right, k)) );
}
int kthSmallest(TreeNode* root, int k) {
return dfs(root, k);
}