您的位置:首页 > 其它

<LeetCode OJ> 230. Kth Smallest Element in a BST

2016-01-22 22:07 295 查看


230. Kth Smallest Element in a BST

My Submissions

Question

Total Accepted: 32753 Total
Submissions: 93019 Difficulty: Medium

给定一个二叉搜索树,写一个函数找到二叉树中第k小的值
Given a binary search tree, write a function
kthSmallest
to
find the kth smallest element in it.
Note:
你应该假设k是安全有效的

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?
Hint:

Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
Tree Binary
Search

Show Similar Problems

分析:

思路首先:

本题还是比较简单的,感觉没达到中等难度,就是一个中序遍历嘛!

对于二叉搜索树而言,中序遍历的结果就是这颗二叉树中值的有序的上升序列

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//time,o(lg(n)),space,o(k)
class Solution {
public:
    void inorderTraversal(TreeNode* root,int k) {    
        if(root){   
            inorderTraversal(root->left,k);  
            result.push_back(root->val);
            if(result.size()==k)
                return;
            inorderTraversal(root->right,k);      
        }
    }
    int kthSmallest(TreeNode* root, int k) {
        inorderTraversal(root,k);
        return result[k-1];
    }
private:
    vector<int> result;
};


迭代法,复杂度均没有变:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//time,o(lg(n)),space,o(k)
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> stk;  //栈中的顺序就是中序遍历顺序    
        TreeNode* pCurNode=root;
        int step=1;
        while (!stk.empty() ||pCurNode)    
        {      
            while(pCurNode)//先把当前节点的所有左子压完,  
            {  
                stk.push(pCurNode);  
                pCurNode=pCurNode->left;  
            }  
  
            pCurNode=stk.top();  //访问当前节点 
            stk.pop(); //栈中去掉此节点
            if(step++==k) 
                return pCurNode->val;
            pCurNode=pCurNode->right;//再访问当前节点的右子树  
        }      
    }
};


学习别人的代码:

int kthSmallest(TreeNode* root, int& k) {
    if (root) {
        int x = kthSmallest(root->left, k);
        return !k ? x : !--k ? root->val : kthSmallest(root->right, k);
    }
}


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50564484

原作者博客:http://blog.csdn.net/ebowtang
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: