230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the th 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小的结点,本来还没什么好思路,

转换思考一下,这不就是求二叉树的中序遍历的第k个结点吗.

直接把94. Binary Tree Inorder Traversal 的代码copy上去,AC。

class Solution {
public:
   
    int kthSmallest(TreeNode* root, int k) {
         vector<int>v;
        stack<TreeNode*> s;
        map<TreeNode*,bool>visit;
        if(root!=NULL)s.push(root);
        while(!s.empty()){
            TreeNode *t=s.top();
            if(!visit[t]&&t->left){
                s.push(t->left);
                visit[t]=true;
            }else{
                v.push_back(t->val); //if(--k==0)return t->val;可以在这里进行return
                s.pop();
                if(t->right)
                    s.push(t->right);
            }
        }
        return v[k-1];
    }
};
这个代码跑了64ms,我们可以修改返回的位置,具体看上面代码注释的地方。

这样时间就缩短为了24ms。

递归的思路:

class Solution {
public:  
    vector<int> v;
    void inorderTraversal(TreeNode* root) {
          if(root!=NULL){
            inorderTraversal(root->left);
              v.push_back(root->val);
            inorderTraversal(root->right);
        }
        return;
    }
    int kthSmallest(TreeNode* root, int k) {
        inorderTraversal(root);
        return v[k-1];
    }
};
然后在网上看到人家写的一个计算节点个数的思路,我觉得也挺好,值得学习下。

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);  
        }  
    }  
};  
出处:http://blog.csdn.net/sunao2002002/article/details/46726245


你可能感兴趣的:(230. Kth Smallest Element in a BST)