平衡二叉树判断:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解法一:递归实现(需要重复遍历节点多次)
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class CheckBalance {
public boolean check(TreeNode root) {
// write code here
if(root==null){
return true;
}
int lh=getDepth(root.left);
int rh=getDepth(root.right);
int diff=lh-rh;
if(diff>1||diff<-1){
return false;
}
return check(root.left)&&check(root.right);
}
//返回一个节点的深度,即该节点到叶子节点的路径最大长度
private int getDepth(TreeNode root){
if(root==null){
return 0;
}
int lh=getDepth(root.left);
int rh=getDepth(root.right);
return lh>rh?(lh+1):rh+1;
}
}
解法二:
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class CheckBalance {
public boolean check(TreeNode root) {
//定义一个引用类型的数据作为平衡标记,通过传引用的方式在递归左右子树时修改平衡标记
boolean[] res=new boolean[1];
//从根节点开始遍历树,遍历过程中修改平衡标记
res[0]=true;
postCheck(root,1,res);
return res[0];
}
public int postCheck(TreeNode root,int depth,boolean[] res){
if(root==null){
return depth;
}
//遍历一次左子树,获取深度(深度已经在参数改变了,目的是为了检查左子树是否平衡)
//若遍历左子树过程中修改了平衡标记为false,则子树非平衡,所以当前结点为根的子树非平衡,不再递归,直接返回
int left_depth=postCheck(root.left,depth+1,res);
if(res[0]==false){
return depth;
}
//若左子树是平衡的,则遍历右子树并获取深度
//若遍历右子树过程中修改了平衡标记为false,则子树非平衡,所以当前结点为根的子树非平衡,不再递归,直接返回
int right_depth=postCheck(root.right,depth+1,res);
if(res[0]==false){
return depth;
}
//若左右子树都是平衡的,则对左右子树深度进行比较,判断当前结点为根的子树是否平衡
if(Math.abs(left_depth-right_depth)>1){//高度差大于1,当前子树不平衡,修改平衡标记
res[0]=false;
}
//用左右子树深度最大者作为自己的高度
return Math.max(left_depth,right_depth);
}
}