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:
Given the following tree[3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree[1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
Note
We can use ResultType to return two parameter in terms of the recursion
class ResultType {
public boolean isBalanced;
public int maxDepth;
public ResultType(boolean isBalanced, int maxDepth) {
this.isBalanced = isBalanced;
this.maxDepth = maxDepth;
}
}
Or we can use -1 to denote that the subtree/tree is not balanced
Code
publicclassSolution {publicbooleanisBalanced(TreeNode root) {returnmaxDepth(root)!=-1; }privateintmaxDepth(TreeNode root) {if (root ==null) {return0; }int left =maxDepth(root.left);int right =maxDepth(root.right);if (left ==-1|| right ==-1||Math.abs(left-right) >1) {return-1; }returnMath.max(left, right) +1; }}
publicclassSolution { /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */publicbooleanisBalanced(TreeNode root) {returnhelper(root).isBalanced; }privateResultTypehelper(TreeNode root) {if (root ==null) {returnnewResultType(true,0); }ResultType left =helper(root.left);ResultType right =helper(root.right);// subtree not balanceif (!left.isBalanced||!right.isBalanced) {returnnewResultType(false,-1); }// root not balanceif (Math.abs(left.maxDepth-right.maxDepth) >1) {returnnewResultType(false,-1); }returnnewResultType(true,Math.max(left.maxDepth,right.maxDepth) +1); }}