题目略
思路一:利用中序遍历
中序遍历BST, 当遍历到第k个时,写入结果。
为了更大地提高效率,在找到第k个时,不再继续递归。有两种方法(我常用的),一:将递归函数设置为有返回类型的,按照返回值决定是否继续递归;二:设置引用参数判断
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int res = 0, cnt = 0;
inorder(root, res, k, cnt);
return res;
}
int inorder(TreeNode* root, int& res, int k, int& i)
{
if(root == nullptr)
return 0;
if(!inorder(root->left, res, k, i))
{
i++;
if(i == k)
{
res = root->val;
return 1;
}
return inorder(root->right, res, k, i);
}
return 1;
}
};
思路二:统计左子树的节点个数
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int leftCount = count(root->left);
if(leftCount == k - 1)
return root->val;
else if(leftCount > k - 1)
return kthSmallest(root->left, k);
else
return kthSmallest(root->right, k - leftCount - 1);
}
int count(TreeNode* root)
{
if(!root)
return 0;
return 1 + count(root->left) + count(root->right);
}
};