• LeetCode 104: Maximum Depth of Binary Tree


    /**
     * 104. Maximum Depth of Binary Tree
     * 1. Time:O(n)  Space:O(h)
     * 2. Time:O(n)  Space:O(h)
     * 3. Time:O(n)  Space:O(h)
     */
    
    // 1. Time:O(n)  Space:O(h)
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null) return 0;
            if(root.left==null && root.right==null) return 1;
            int maxLevel = Integer.MIN_VALUE;
            if(root.left!=null)
                maxLevel = Math.max(maxLevel,maxDepth(root.left));
            if(root.right!=null)
                maxLevel = Math.max(maxLevel,maxDepth(root.right));
            return maxLevel+1;
        }
    }
    
    // 2. Time:O(n)  Space:O(h)
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null) return 0;
            Stack<TreeNode> stack = new Stack<>();
            int maxLevel=Integer.MIN_VALUE,level=0;
            TreeNode last=null;
            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)
                        maxLevel = Math.max(maxLevel,level);
                    last = stack.pop();
                    level--;
                }
            }
            return maxLevel;
        }
    }
    
    // 3. Time:O(n)  Space:O(h)
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null) return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            int maxLevel = 0;
            while(!queue.isEmpty()){
                maxLevel++;
                int size = queue.size();
                for(int i=0;i<size;i++){
                    TreeNode tmp = queue.poll();
                    if(tmp.left!=null)
                        queue.add(tmp.left);
                    if(tmp.right!=null)
                        queue.add(tmp.right);
                }
            }
            return maxLevel;
        }
    }
    
  • 相关阅读:
    [LOJ 6436][PKUSC2018] 神仙的游戏
    [BZOJ 2653] middle
    [WC2018] 州区划分
    [BZOJ 4556][Tjoi2016&Heoi2016]字符串
    [BZOJ 3514]Codechef MARCH14 GERALD07加强版 (CHEF AND GRAPH QUERIES)
    [BZOJ 4573][ZJOI 2016]大♂森林
    Problem 2322. -- [BeiJing2011]梦想封印
    [BZOJ 2555] SubString
    [日常] NOIWC2019 冬眠记
    [BZOJ 4036][HAOI2015]按位或
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849314.html
Copyright © 2020-2023  润新知