思路:
二叉搜索树中序遍历是有序的,所以我们对二叉树进行中序遍历,统计k就可以了。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int k;
int res;
int kthSmallest(TreeNode* root, int _k) {
k = _k;
dfs(root);
return res;
}
bool dfs(TreeNode* root){
if(!root) return false;
if(dfs(root->left)) return true;
if(--k == 0){
res = root->val;
return true;
}
return dfs(root->right);
}
};
评论区