• <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;
        }
    }
  • 相关阅读:
    HDU1548:A strange lift
    hdu1978_How many ways dfs+记忆化搜索
    HDU1518:Square(DFS)
    HDU ACM 1495 非常可乐(广搜BFS)
    HDU1372:Knight Moves(BFS)
    662_二叉树最大宽度
    590_N叉树的后序遍历
    一直在坚持
    动态链接库DLL的操作顺序
    最近木马的查杀方法/各类杀毒软件的使用
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11901061.html
Copyright © 2020-2023  润新知