码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode]Kth Smallest Element in a BST

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

标签:leetcode   二叉搜索树   

//用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

标签:leetcode   二叉搜索树   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!