您的位置:首页 > 其它

【LectCode】230. Kth Smallest Element in a BST

2017-07-15 00:11 260 查看
题目:

Given a binary search tree, write a function 
kthSmallest
 to find the kth
smallest element in it.

Note: 

You may assume k is always valid, 1 ? k ? BST's total elements.

Follow up:

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
解题思路:题目要求数的第k小的值,我们知道二分搜索树是按照值的大小分布在父节点的两边的,即若左子树的节点数为n,则根为第n+1小的值;因此,我先写一个计算树的节点数的函数,然后先计算左子树的节点数leftsize,若k == leftsize+1,则返回跟节点的值;若k <= leftsize,则进入左子树的递归;若k >= leftsize+1,则进入右子树的递归,并把k的值修改为k - leftsize -1。

解答:

/**

 * 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 {

public:

    int kthSmallest(TreeNode* root, int k) {

         if(root == NULL){

        return 0;
}
int leftsize = cal(root->left);
if(k == leftsize +1){
return root->val;
}
else if(k <= leftsize){
return kthSmallest(root->left,k);
}
else{
return kthSmallest(root->right,k - leftsize -1);
}

    }

     int cal(TreeNode* root){

        if(root == NULL){

        return 0;
}
else{
return 1 + cal(root->left) + cal(root->right);
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: