题目
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.
实现
public class balanced_binary_tree {
public boolean isBalanced(Node root) {
if(root==null){
return true;
}
int l=depth(root.left);
int r=depth(root.right);
if(l-r>1 || r-l>1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int depth(Node node) {
if(node==null){
return 0;
}
int l=depth(node.left);
int r=depth(node.right);
return Math.max(l,r)+1;
}
}