zoukankan      html  css  js  c++  java
  • <Tree> 110 124

    110. Balanced Binary Tree

    方法是如果我们发现子树不平衡,则不计算具体的深度,而是直接返回-1。那么优化后的方法为:对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1,此方法时间复杂度O(N),空间复杂度O(n)

    class Solution {
        public boolean isBalanced(TreeNode root) {
            return height(root) != -1;   
        }
        
        private int height(TreeNode root){
            if(root == null)
                return 0;
            int leftHeight = height(root.left);
            if(leftHeight == -1)
                return -1;
            int rightHeight = height(root.right);
            if(rightHeight == -1)
                return -1;
            if(leftHeight - rightHeight < -1 || leftHeight - rightHeight > 1)
                return -1;
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    124. Binary Tree Maximum Path Sum

    只有根节点才能包括左右子树的数值,如果是return则只能保存到左右子树中最大的一个分支

    class Solution {
    
        public int maxPathSum(TreeNode root) {
            if(root == null) return 0;
            int[] maxPath =new int[] {Integer.MIN_VALUE};
            dfs(root, maxPath);
            return maxPath[0];
        }
        
        private int dfs(TreeNode root, int[] maxPath){
            if(root == null) return 0;
            int left = Math.max(dfs(root.left, maxPath), 0);
            int right = Math.max(dfs(root.right, maxPath), 0);
            maxPath[0] = Math.max(maxPath[0], root.val + left + right);
            return Math.max(left, right) + root.val;
        }
    }
  • 相关阅读:
    数列分段divide
    精度计算(保留几位小数)
    洛谷P1119灾后重建
    暴雨rain
    石子游戏stone
    化学家chemist
    【ybtoj】【质数和约数】合并集合
    【ybtoj】【质数和约数】质数距离
    【ybtoj】【质数和约数】不定方程
    【再见OI】9.23模拟总结
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11901061.html
Copyright © 2011-2022 走看看