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);
        }
    }
    
  • 相关阅读:
    将16进制的颜色转为rgb颜色
    css3选择
    css写复选框
    关于瀑布流
    关于CSS3属性transition的触发
    单行文本两端对齐
    jQuery插件——下拉选择框
    CSS3帧动画
    Vuejs自定义全局组件--loading
    Sublime text开发Quick-Cocos2d-x-3.x环境搭建(Windows)
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849301.html
Copyright © 2011-2022 走看看