package class08;
/*
* 可能性:head有无关
* 无关:左右树的最大搜素子二叉树大小
* 有关:左右都属搜索二叉树,且左边的最小于head,右边最小大于head
*
* 统一:
* 左边:最大子搜索树size,左边是不是搜索二叉树,max
* 右边:最大子搜索树size,它整体是不是搜搜二叉树,min
* 全集:最大子搜索树size,是不是整体是,max和min
*
* */
public class MaxSubSearchBT {
public static class Node{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
public static class Info{
int maxSearchSize;
boolean isAllBST;
int min;
int max;
public Info(int maxSearchSize, boolean isAllBST, int min, int max) {
this.maxSearchSize = maxSearchSize;
this.isAllBST = isAllBST;
this.min = min;
this.max = max;
}
}
public static Info process(Node head){
if(head==null){
//不好确定min和max可以返回空,但是每次用信息时候要判空
//所以每个信息要有初始值
return null;
}
Info leftInfo=process(head.left);
Info rightInfo=process(head.right);
int min=head.value;
if(head.left!=null){
min=leftInfo.min;
}
if(head.right!=null){
min=Math.min(min,rightInfo.min);
}
int max=head.value;
if(head.left!=null){
max=leftInfo.max;
}
if(head.right!=null){
max=Math.max(max,rightInfo.max);
}
int maxSearchSize = 0;
if(head.left!=null){
maxSearchSize= leftInfo.maxSearchSize;
}
if(head.right!=null){
maxSearchSize=rightInfo.maxSearchSize;
}
//一般最后处理和head有关的答案,因为要用到前面的信息
boolean isAllBST = false;
if(
(head.left==null?true:isAllBST)&&(head.right==null?true:isAllBST)
&&(head.value>leftInfo.max)&&(head.value<rightInfo.min)
){
isAllBST=true;
maxSearchSize=(head.left==null?0:leftInfo.maxSearchSize)
+(head.right==null?0:rightInfo.maxSearchSize)+1;
}
return new Info(maxSearchSize,isAllBST,min,max);
}
}
二叉树套路4
最新推荐文章于 2024-11-01 15:19:21 发布