题目如上:
/**
* 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 {
private:
int kth;
public:
int kthSmallest(TreeNode* root, int k) {
bst(root,k);
return kth;
}
void bst(TreeNode* root,int& k){
if(root==nullptr)
return ;
bst(root->left, k);
k--; //中序遍历
if(k==0)
{
kth= root->val;
return;
}
bst(root->right,k);
return;
}
};