/**
* 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 solve(TreeNode* root){
if(root==NULL) return 0;
return 1+solve(root->left)+solve(root->right);
}
int kthSmallest(TreeNode* root, int k) {
if(root==NULL) return 0;
int leftsize = solve(root->left);
if(k==leftsize+1){
return root->val;
}else if(leftsize>=k){ //在左分支
return kthSmallest(root->left, k);
}else{ //在右分支
return kthSmallest(root->right, k-leftsize-1); //1是root
}
}
};
leetcode230+Kth Smallest Element in a BST+dfs
最新推荐文章于 2024-08-23 01:05:03 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)