方法一:自底向上
思路:Solve方法仍然是在求高度
public boolean isBalanced(TreeNode root){
return Solve(root)!=-1;
}
public int Solve(TreeNode root){
if(root==null) return 0;
int left=Solve(root.left);
if(left==-1) return -1;//剪枝
int right=Solve(root.right);
if(right==-1) return -1;//剪枝
return Math.abs(left-right)<2?Math.max(left,right)+1:-1;
}
方法二:自顶向下
思路可以参考求二叉树的深度。
求二叉树深度的递归算法:
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
代码如下:
public boolean isBalanced(TreeNode root){
if(root==null) return true;
return Math.abs(depth(root.left)-depth(root.right))<2&&isBalanced(root.left)&&isBalanced(root.right);
}
public int depth(TreeNode root){
if(root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}