给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
题解:二叉搜索树,使用中序遍历,得到从小到大的数,每递归一次,count++;当count==k时,得到第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 count;
int ans;
int kthSmallest(TreeNode* root, int k) {
inorder(root,k);
return ans;
}
void inorder(TreeNode* root,int k){
if(root==NULL) return ;
if(root!=NULL){
inorder(root->left,k);
count++;
if(count==k) ans=root->val;
inorder(root->right,k);
}
}
};