首页 > 其他 > 详细

leetcode 230. Kth Smallest Element in a BST

时间:2019-04-09 12:34:40      阅读:124      评论:0      收藏:0      [点我收藏+]

https://www.cnblogs.com/grandyang/p/4620012.html

这个题其实就是中序遍历第k个数就好了,代码最好写的就是非递归的方式,在stack里面找第k个就好了。也可以使用递归的方式:

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        return Smallest(root,k);
    }
    int Smallest(TreeNode* root,int& k){
        if(root == NULL)
            return -1;
        int num = Smallest(root->left,k);
        if(k == 0)
            return num;
        if(--k == 0)
            return root->val;
        return Smallest(root->right,k);
    }
};

注意:这种递归的方法在NULL时候返回-1,如果找到了数字,返回值就会以当前的结果替代-1.

 

leetcode 230. Kth Smallest Element in a BST

原文:https://www.cnblogs.com/ymjyqsx/p/10675805.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!