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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
判断一棵二叉树是否为二叉平衡树
二叉平衡树的条件是左子树和右子树都是二叉平衡树,并且左右高度差不能超过1
这时候需要两个返回值,一个是boolean(是否是二叉平衡树),一个是树的高度
因为函数只能返回一个值,高度是>0的,所以用高度=-1来表示不是二叉平衡树
*注意根节点为null的树也是二叉平衡树
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (treeHeight(root) == -1) {
return false;
}
return true;
}
public int treeHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = treeHeight(root.left);
int rightHeight = treeHeight(root.right);
if (leftHeight == -1 || rightHeight == -1 ) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return (Math.max(leftHeight, rightHeight) + 1);
}