要记得剪枝,不然会超时
public class Solution {
public boolean isBalanced(TreeNode root) {
return rec(root)!=-1;
}
private int rec(TreeNode root) {
if(root==null) return 0;
int l = rec(root.left);
int r = rec(root.right);
if(l==-1 || r==-1 || Math.abs(l-r) > 1) return -1;
return Math.max(l, r)+1;
}
}