230. 二叉搜索树中第K小的元素
题目描述
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
示例 2:
思路
中序遍历是递增序列,用变量i记录是第几个元素,利用find记录是否找到结果,来提前终止遍历过程。
代码
/**
* 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 i = 0;
bool find = false;
int result = -1;
_kthSmallest(root,k,i,find,result);
return result;
}
void _kthSmallest(TreeNode* root, int k, int& i,bool& find,int& result){
if(root == NULL || find){
return;
}
_kthSmallest(root->left,k,i,find,result);
if(++i == k){
result = root->val;
find = true;
return;
}
_kthSmallest(root->right,k,i,find,result);
}
};
算法复杂度
时间复杂度:O(N)
空间复杂度:O(N)