public class Solution {
// 定义变量记录是否是平衡二叉树,默认为true,后面不符合条件则置false
private boolean isBlanceTree = true;
public boolean IsBalanced_Solution(TreeNode root) {
// 判断该树是否为平衡二叉树:其实就是求左、右子树的的深度
calDepth(root);
return isBlanceTree;
}
public int calDepth(TreeNode root){
// 递归出口
if(root == null) return 0;
// 递归求解左右子树的深度
int l = calDepth(root.left);
if(l == -1) return -1;
int r = calDepth(root.right);
if(r == -1) return -1;
int depth = Math.max(l, r) + 1;
if(Math.abs(l-r)>1){ // 求左、右子树的深度差,如果有任一个左右子树不符合平衡树的条件,返回-1
isBlanceTree = false;
return -1;
}
return depth;
}
}