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 binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * 用一个INT 表示两种状态 当返回值大于等于0时 表示当前节点的深度,当返回值是-1时,表示不是平衡二叉树 * @param root * @return */ public int isBalancedHelper(TreeNode root) { if (root==null) { return 0; } int l = isBalancedHelper(root.left); int r = isBalancedHelper(root.right); if (l==-1||r==-1) { //左右子树有一个不是平衡二叉树,就不是平衡二叉树 return -1; } if (Math.abs(l-r)>1) { //左右子树高度差大于1 不是平衡二叉树 return -1; } else { return Math.max(l, r) + 1; } } /** * 平衡二叉树 左右子树是平衡二叉树 且 左右子树高度差小于等于1 * @param root * @return */ public boolean isBalanced(TreeNode root) { return isBalancedHelper(root)>=0; } }