一:
什么是平衡二叉树?
平衡二叉树就是说,对于二叉树的每一个节点,左右子树的高度差小于等于1。
这样的二叉树被称为平衡二叉树。
怎么递归?
二叉树要满足平衡需要做到三点:
1.左子树是平衡二叉树
2.右子树是平衡二叉树
3.左右子树的高度差小于等于1.
那么我们需要子树传递的信息就包含两个方面:是否是平衡二叉树和高度。
如果子树可以把这两个信息传递给根节点,我们就可以判断出这个二叉树是否是平衡二叉树。
public static boolean isBanlanced(NodeTwo head) {
return process(head).isBanlanced;
}
public static ReturnType process(NodeTwo head) {
//如果树为空,那就是平衡且高度为0
if(head == null) {
return new ReturnType(true, 0);
}
//拿到左右两棵子树的信息
ReturnType l = process(head.left);
ReturnType r = process(head.right);
//求出本节点的高度
int height = Math.max(l.height, r.height)+1;
//判断本节点是否平衡
boolean isBanlanced = (l.isBanlanced&&r.isBanlanced&&(Math.abs(l.height-r.height))<2);
return new ReturnType(isBanlanced, height);
}
//子树需要传递的消息的类
//是否平衡 高度
public static class ReturnType{
boolean isBanlanced;
int height;
public ReturnType(boolean ib,int h) {
isBanlanced = ib;
height = h;
}
}
二:搜索二叉树
public static boolean isSearch(NodeTwo head) {
return process(head).isSearch;
}
public static ReturnType process(NodeTwo head) {
if(head == null) {
return null;
}
int max = head.value;
int min = head.value;
boolean isSearch = true;
ReturnType l = process(head.left);
ReturnType r = process(head.right);
if(r!=null) {
max = Math.max(max, r.max);
min = Math.min(min,r.min);
}
if(l!=null) {
min = Math.min(min, l.min);
max = Math.max(max, l.max);
}
//左树不为空,左树不是搜索二叉树或者左树的最大值大于等于当前节点的值
if(l!=null && (!l.isSearch || l.max>= head.value) ) {
isSearch = false;
}
if(r!=null && (!r.isSearch || r.min<= head.value)) {
isSearch = false;
}
return new ReturnType(max, min, isSearch);
}
public static class ReturnType{
int max;
int min;
boolean isSearch;
public ReturnType(int max1,int min1,boolean is) {
max = max1;
min = min1;
isSearch = is;
}
}
三:满二叉树
一棵满二叉树满足 节点数 = 2的高度次幂-1
所以需要从子树得到的消息就是 高度和节点数。
public static boolean isFull(NodeTwo head) {
if(head == null) {
return true;
}
ReturnType r = process(head);
return r.nodes == (1 << r.height - 1);
//(1 << r.height)的意思就是1左移多少位也就是求2的x次幂。
}
public static ReturnType process(NodeTwo head) {
if(head == null) {
return new ReturnType(0, 0);
}
ReturnType l = process(head.left);
ReturnType r = process(head.right);
int height = Math.max(l.height, r.height) + 1;
int nodes = l.nodes + r.nodes +1;
return new ReturnType(height, nodes);
}
public static class ReturnType{
int height;
int nodes;
public ReturnType(int height,int nodes) {
this.height = height;
this.nodes = nodes;
}
}
其实这就是一种二叉树递归套路:
判断一棵二叉树是否满足某个条件。
就看需要从子树中得到什么样的信息。
不断递归从子树中拿到这些信息
最终就可以得到想要的信息,然后再加入根节点进行判断是否满足条件。