在递归过程中,对当前节点进行情况划分
1)满二叉树(无缺口)
2)有缺口
1))左树有缺口(左树是完全二叉树、右树是满二叉树,并且左树高-右树高==1)
2))左树刚好满了(左树是满二叉树、右树是满二叉树,并且左树高-右树高==1)
3))右树有缺口(左树是满二叉树、右树是完全二叉树,并且左树高度与右树高度一样)
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
value = data;
}
}
//定义递归主函数需要返回的参数
public static class Info{
public boolean isFull;
public boolean isCBT;
public int height;
public Info(boolean full, boolean cbt, int h){
isFull = full;
isCBT = cbt;
height = h;
}
}
//主方法
public static Info process(Node X){
if(X == null){
return new Info(true, true, 0);
}
Info leftInfo = process(X.left);
Info rightInfo = process(X.right);
int heigth = Math.max(leftInfo.height, rightInfo.height) + 1;
boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height==rightInfo.height;
boolean isCBT = false;
if(isFull){
isCBT = true;
}else{
if(leftInfo.isCBT && rightInfo.isCBT){
if(leftInfo.isCBT && rightInfo.isFull && leftInfo.height-rightInfo.height==1){
isCBT = true;
}
if(leftInfo.isFull && rightInfo.isFull && leftInfo.height-rightInfo.height==1){
isCBT = true;
}
if(leftInfo.isFull && rightInfo.isCBT && leftInfo.height==rightInfo.height){
isCBT = true;
}
}
}
return new Info(isFull, isCBT, heigth);
}