zoukankan      html  css  js  c++  java
  • LeetCode 230: Kth Smallest Element in a BST

    /**
     * 230. Kth Smallest Element in a BST
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(h+k)  Space:O(h+k)
     * 3. Time:O(h+k)  Space:O(h+k)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            List<Integer> res = new ArrayList<>();
            helper(root,res);
            return res.get(k-1);
        }
        
        private void helper(TreeNode root, List<Integer> res){
            if(root==null) return;
            helper(root.left,res);
            res.add(root.val);
            helper(root.right,res);
        }
    }
    
    // 2. Time:O(h+k)  Space:O(h+k)
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<>();
            while(true){
                while(root!=null){
                    stack.push(root);
                    root=root.left;
                }
                root = stack.pop();
                if(--k == 0) return root.val;
                root = root.right;
            }
        }
    }
    
    // 3. Time:O(h+k)  Space:O(h+k)
    class Solution {
        
        private int cnt=0;
        private int res;
        
        public int kthSmallest(TreeNode root, int k) {
            helper(root,k);
            return res;
        }
        
        private void helper(TreeNode root, int k){
            if(root==null) return;
            helper(root.left,k);
            if(++cnt == k){
                res = root.val;
            }
            helper(root.right,k);
        }
    }
    
  • 相关阅读:
    redis(lettuce)
    Dubbo与SSM整合(认证授权)步骤
    maven常用命令
    Dubbo(RPC框架)
    SpringCache
    mybatis(SSM整合)
    java设计模式-命令模式
    java设计模式-原型模式
    java设计模式-职责链模式
    java设计模式-建造者模式
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849301.html
Copyright © 2011-2022 走看看