题目:
题解:
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int search_num(struct TreeNode* root, int k, int *result, int num)
{
if(num == k + 1)
{
return k + 1; // 已找到就不往下跑了
}
if(root->left)
{
num = search_num(root->left, k, result, num);
}
if(num == k)
{
*result = root->val;
return k + 1; // 已找到就不往下跑了
}
num++;
if(root->right)
{
num = search_num(root->right, k, result, num);
}
return num;
}
int kthSmallest(struct TreeNode* root, int k) {
int result = 0;
search_num(root, k, &result, 1); // 开始寻找
return result;
}