需要一个辅助方法,计算树的高度
public int height(TreeNode root) {
if(root == null) return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return leftHeight>rightHeight?(leftHeight+1):(rightHeight+1);
}
判断树是否为平衡二叉树
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int diff = height(root.left) - height(root.right);
if(diff<-1 || diff>1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
}