首页 > 其他 > 详细

[Leetcode]Kth Smallest Element in a BST

时间:2015-07-29 06:26:00      阅读:207      评论:0      收藏:0      [点我收藏+]

//用search计算左子树的节点个数,加上根节点本身若为k则输出,否则

//(1)若k大于目前个数,则k-左子树节点个数,再计算右子树

//(2)若k小于目前个数,则直接计算左子树

/**

 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int result=0;
    int search(TreeNode* root)
    {
        if(root==NULL)
        return 0;
        return 1+search(root->left)+search(root->right);
    }
public:
    int kthSmallest(TreeNode* root, int k) {
        int result;
        int count=search(root->left)+1;
        if(count==k)return root->val;
        else if(count>k)kthSmallest(root->left,k);
        else if(count<k)kthSmallest(root->right,k-count);
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]Kth Smallest Element in a BST

原文:http://blog.csdn.net/yang_snow/article/details/47118833

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