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.
* Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclass{ publicbooleanisBalanced(TreeNode root){ if (root == null || (root.left == null && root.right == null)) returntrue; if (dp(root) < 0) returnfalse; else { returntrue; }
}
publicintdp(TreeNode root){
if (root == null) return0; int a = dp(root.left); int b = dp(root.right); if (a == -1 || b == -1) { return -1; } int l = a > b ? a - b : b - a; if (l > 1) return -1; else { return Math.max(a, b) + 1; }
近期评论