1、从顶往下(暴力解法):时间复杂度较高(产生了大量重复的计算)
代码如下:
public boolean isBalanced(TreeNode root){
//从顶往下
//递归终止条件
if(root == null){
return true;
}
int left = height(root.left);
int right = height(root.right);
//判断绝对值大于1,相当于Math.abs(left - right) > 1
int abs = left - right;
if(abs > 1 || abs < -1){
return false;
}else{
//否则递归当前节点的左右节点
return isBalanced(root.left) && isBalanced(root.right);
}
}
//计算root为根节点的树的高度
public int height(TreeNode root){
//递归终止条件
if(root == null){
return 0;
}
return Math.max(height(root.left),height(root.right)) + 1;
}
2、从底往上(提前阻断)
代码如下:
//定义全局变量res
boolean res = true;
public boolean isBalanced(TreeNode root){
helper(root);
return res;
}
public int helper(TreeNode root){
//递归终止条件
if(root == null){
return 0;
}
int left = helper(root.left) + 1;
int right = helper(root.right) + 1;
//实现提前阻断
if(Math.abs(left - right) > 1){
//将res置为false
res = false;
}
return Math.max(left,right);
}
通过全局变量res,将res初始化为true,在helper方法中,从底部向上回溯的过程中,判断每一棵子树是不是平衡二叉树,若不是,就将res赋值为false 。