Balanced Binary Tree
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.
平衡二叉树Balanced binary tree的定义是:任意节点的左子树的高度和右子树的高度之差小于等于1. 那么一个二叉树是平衡二叉树 当且仅当 (1. 左子树是平衡二叉树, 2. 右子树是平衡二叉树; 3, 左右子树的高度之差小于等于1)
public boolean isBalanced(TreeNode root) {
if (getMaxDepth(root) == -1) {
return false;
}
return true;
}
public int getMaxDepth(TreeNode node) {
if (node == null) {
return 0;
}
int left = getMaxDepth(node.left);
int right = getMaxDepth(node.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}