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);
        }
    }
    
  • 相关阅读:
    词云
    结巴分词
    重复值处理
    异常值判断
    MySQL基本使用
    缺失值处理
    fit_transform和transform的区别
    sklearn学习笔记之简单线性回归
    图解机器学习
    Unity---UNet学习(1)----基本方法介绍
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849301.html
Copyright © 2011-2022 走看看