93. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example
Example 1:
Input: tree = {1,2,3}
Output: true
Explanation:
This is a balanced binary tree.
1
/
2 3
Example 2:
Input: tree = {3,9,20,#,#,15,7}
Output: true
Explanation:
This is a balanced binary tree.
3
/
9 20
/
15 7
Example 3:
Input: tree = {1,#,2,3,4}
Output: false
Explanation:
This is not a balanced tree.
The height of node 1's right sub-tree is 2 but left sub-tree is 0.
1
2
/
3 4
分治法:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ public boolean isBalanced(TreeNode root) { return maxDepth(root) != -1; } public int maxDepth(TreeNode root) { if (root == null) { return 0; } int right = maxDepth(root.right); int left = maxDepth(root.left); if (right == -1 || left == -1 || Math.abs(right-left) > 1) { return -1; } return Math.max(right,left) + 1; } }