题目描述
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.
分析
判断二叉树是否平衡,规则如下:
左子树深度和右子树深度相差不大于1
核心代码:
return Math.abs(height(root.left) - height(root.right)) <= 1
&& isBalanced(root.left) && isBalanced(root.right);
代码
public static boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(height(root.left) - height(root.right)) <= 1
&& isBalanced(root.left) && isBalanced(root.right);
}
static int height(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(height(node.left), height(node.right)) + 1;
}