Q:
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.
Analysis:
使用递归计算树的高度,若当前结点满足平衡二叉树性质,仍需要判断该结点的左右子树是否满足平衡二叉树。
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int left = deep(root.left);
int right = deep(root.right);
// 若本节点满足平衡二叉树,判断左右子树是否满足
if (Math.abs(left - right) <= 1) {
return isBalanced(root.left) && isBalanced(root.right);
} else {
return false;
}
}
public static int deep(TreeNode root) {
int depthLeft, depthRight;
if (root == null) {
return 0;
}
if (root.right == null && root.left == null) {
return 1;
} else {
depthLeft = deep(root.left);
depthRight = deep(root.right);
}
return 1+(depthLeft>depthRight?depthLeft:depthRight);
}
}