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.
Solution:
The 3 requirements for a balanced tree are:
1. left subtree is balanced
2. right subtree is balanced
3. the depth of two subtrees differ by no more than 1
Tips:
When the tree is not balanced, return -1 rather than the real depth in the helper method.
public boolean isBalanced(TreeNode root) {
return getDepth(root)>=0;
}
public int getDepth(TreeNode root){
if(root==null) return 0;
int leftD=getDepth(root.left);
int rightD=getDepth(root.right);
if(leftD<0 || rightD<0 || Math.abs(leftD-rightD)>1) return -1;
return Math.max(leftD,rightD)+1;
}
No comments:
Post a Comment