给定一个二叉搜索树,编写一个函数 kthSmallest
来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 输出: 3
进阶:
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest
函数?
分析:
是二叉搜索树,所以它的中序遍历是一个递增的序列。要找到第K小的值,只需要找到中序遍历结果的第K个数。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
// 中序遍历
int result = 0;
int curr_count = 0;
in_order(root, k, curr_count, result);
return result;
}
void in_order(TreeNode* root, int k, int& curr_count, int& result){
if(root == NULL || k<curr_count) return;
in_order(root->left, k, curr_count, result);
curr_count += 1;
if(k == curr_count){
result = root->val;
return;
}
in_order(root->right, k, curr_count, result);
}
};