Thought:
To prevent redundant computation, we'd better first examine the flag of the left subtree and then the right one.
-1 means unbalanced and if not -1 it means the height.
Code:
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) {
return true;
}else{
return flag(root) == -1? false: true;
}
}
public int flag(TreeNode root) {
if(root == null) {
return 0;
}else{
int lFlag = flag(root.left);
if(lFlag == -1) return -1;
int rFlag = flag(root.right);
if(rFlag == -1) return -1;
return Math.abs(lFlag - rFlag) <= 1? Math.max(lFlag, rFlag) + 1: -1;
}
}
}
No comments:
Post a Comment