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 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.
tag: binary tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class MyTree{
boolean balanced;
int height;
public MyTree(boolean balanced, int height){
this.balanced = balanced;
this.height = height;
}
}
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return helper(root).balanced;
}
private MyTree helper(TreeNode root){
if (root == null){
return new MyTree(true, 0);
}
MyTree leftTree = helper(root.left);
MyTree rightTree = helper(root.right);
boolean balanced = leftTree.balanced && rightTree.balanced && Math.abs(leftTree.height - rightTree.height) <= 1;
int height = Math.max(leftTree.height, rightTree.height) + 1;
return new MyTree(balanced, height);
}
}