Question
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.
Java Code
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int depth1 = maxDepth(root.left);
int depth2 = maxDepth(root.right);
//如果当前节点的左右子树的深度差小于1,则继续判断左右子节点各自的左右子树的深度差是否小于1
if( -2 < depth1 - depth2 && depth1 - depth2 < 2)
return isBalanced(root.left) && isBalanced(root.right);
else
return false;
}
说明
- TreeNode类的定义和maxDepth函数见题目Maximum Depth of Binary Tree