zoukankan      html  css  js  c++  java
  • [LeetCode] Kth Smallest Element in a BST

    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?

    Hint:

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

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

    分析:

    方法一:中序遍历+直接去第k个;

    方法二:使用中序遍历框架,当检测到第k个时,直接返回,空间 复杂度节省一些。

    中序遍历的code

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            
            vector<int> result;
            stack<TreeNode*> stack;
            
            TreeNode *p = root;
            
            while( NULL != p || !stack.empty())
            {
                while(NULL != p)
                {
                    result.push_back(p->val);
                    
                    stack.push(p);
                    p = p->left;
                }
                
                if(!stack.empty())
                {
                    p= stack.top();
                    stack.pop();
                    
                    p=p->right;
                }
            }
            
            return result;
        }
        
    };

    改进的使用中序遍历来解决此问题的code:

    class Solution {
        public:
            int kthSmallest(TreeNode* root, int k) {
        
                stack<TreeNode*> st; 
                TreeNode* p = root;
    
                int cnt = 0;
    
                while(p != NULL || !st.empty())
                {   
                    while(p)
                    {   
                        st.push(p);
                        p = p->left;
                    }   
    
                    if(!st.empty())
                    {   
                        p = st.top();
                        st.pop();
    
                        cnt ++; 
                        if(cnt == k)
                        {   
                            return p->val;
                        }   
    
                        p = p->right;
    
                    }   
                }
                return -1;
    
            }
    };
  • 相关阅读:
    (转)6 个重构方法可帮你提升 80% 的代码质量
    (转)卸载和安装LINUX上的JDK
    (转)一些国外优秀的elasticsearch使用案例
    (转)Redis 集群方案
    (转)理想化的 Redis 集群
    (转)Hprose与WCF在云计算平台Azure上的对决
    (转).NET技术+25台服务器怎样支撑世界第54大网站
    Hbase split的过程以及解发条件
    test
    HTTP和HTTPS详解
  • 原文地址:https://www.cnblogs.com/diegodu/p/4624497.html
Copyright © 2011-2022 走看看