• LeetCode 111: Minimum Depth of Binary Tree


    /**
     * 111. Minimum Depth of Binary Tree
     * 1. Time:O(n)  Space:O(h)
     * 2. Time:O(n)  Space:O(h)
     */
    
    // 1. Time:O(n)  Space:O(h)
    class Solution {
        public int minDepth(TreeNode root) {
            if(root==null) return 0;
            if(root.left==null && root.right==null) return 1;
            int min = Integer.MAX_VALUE;
            if(root.left!=null)
                min = Math.min(minDepth(root.left),min);
            if(root.right!=null)
                min = Math.min(minDepth(root.right),min);
            return min+1;
        }
    }
    
    // 2. Time:O(n)  Space:O(h)
    class Solution {
        public int minDepth(TreeNode root) {
            if(root==null) return 0;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode last = null;
            int level=0,minLevel=Integer.MAX_VALUE;
            while(root!=null || !stack.isEmpty()){
                while(root!=null){
                    stack.push(root);
                    level++;
                    root = root.left;
                }
                TreeNode tmp = stack.peek();
                if(tmp.right!=null && tmp.right!=last)
                    root = tmp.right;
                else{
                    if(tmp.left==null && tmp.right==null)
                        minLevel = Math.min(minLevel,level);
                    last = stack.pop();
                    level--;
                }
            }
            return minLevel;
        }
    }
    
  • 相关阅读:
    Go Map
    Go XORM
    Go切片
    Go函数
    dockerfile常用指令
    Goroutine并发控制
    Go 格式转换
    Go 常用知识点及实例
    Go 时间
    Go error
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849334.html
Copyright © 2020-2023  润新知