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; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int left=depth(root.left);
int right=depth(root.right);
if(Math.abs(left-right)>1)
return false;
else
return(isBalanced(root.left) && isBalanced(root.right));
}
public int depth(TreeNode root){
if(root==null) return 0;
else{
int left = depth(root.left)+1;
int right = depth(root.right)+1;
return left>right? left: right;
}
}
}