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; } }