1、题目描述
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.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
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?
2、问题描述:
- 二叉搜索树的遍历,求第k个结点的值。
3、问题关键:
- 二叉树的中序遍历,是从小到达排列的,所以,只需要中序遍历到第k个就可以了。
- 中序遍历,第k个,如果在根结点的左边,那么k <= 0; 如果左子树遍历完了k=1,那么就是返回root的值,否则遍历右子树。
4、C++代码:
class Solution {
public:
int dfs(TreeNode* root, int &k) {
if (!root) return 0;
int left = dfs(root->left, k);//遍历左子树
if (k <= 0) return left;//如果左子树存在,那么返回左子树的值。
if (--k == 0) return root->val;//如果遍历左子树
return dfs(root->right, k);
}
int kthSmallest(TreeNode* root, int k) {
return dfs(root, k);
}
};