110. 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 ofeverynode never differ by more than 1.
Analysis:
We can create a method to find the maxHeight of root.
usually such method, just do like" return Math.max(maxHeight(root.left), maxHeight(root.right)) +1"
but this one, we can make it, so that, if |leftHeight - rightHeight| > 1, return -1. and whenever -1 is returned, we return directly -1 without further traverse. This way, it is bubbling up whenever there is "un-balanced" subtree is detected.
Complexity:
Time: O(N) - bottom up approach, whenever un-balance is detected, we stop further traverse.
Space: O(logn)
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
{
return true;
}
return maxHeight(root) != -1;
}
private int maxHeight(TreeNode root)
{
if(root == null)
{
return 0;
}
int left = maxHeight(root.left);
if(left == -1)
{
return -1;
}
int right = maxHeight(root.right);
if(right == -1)
{
return -1;
}
if(Math.abs(left - right) > 1)
{
return -1;
}
return Math.max(left, right) + 1;
}
}