leetcode + BST中第K小数目,递归

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/79959051
点击打开链接
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    int calcTreeSize(TreeNode* root)
    {
        if(root == NULL){
            return 0;
        }
        return 1+calcTreeSize(root->left) + calcTreeSize(root->right);
    }
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL) return 0;
        int leftSize = calcTreeSize(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);
        }
    }
};


阅读更多

没有更多推荐了,返回首页