Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
Ans:a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
public boolean isBalanced(TreeNode root) {
if(root == null) {
return true;
}
int lHeight = -1, rHeight = -1;
if(root.left != null) {
lHeight = height(root.left);
}
if(root.right != null) {
rHeight = height(root.right);
}
if(Math.abs(lHeight-rHeight)>1) {
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
private int height(TreeNode T) {
if(T == null) {
return -1;
}
if(T.left==null && T.right==null) {
return 0;
}
return Math.max(height(T.left),height(T.right))+1;
}
No comments:
Post a Comment