// 返回值结构
public static class ReturnData{
public int max;
public int min;
public Boolean isBST;
public ReturnData(int max, int min, Boolean isBST) {
this.max = max;
this.min = min;
this.isBST = isBST;
}
}
// 树形DP:先列出搜索树条件,然后向左树要信息,向右树要信息,罗列可能性。
// 条件: 左搜 右搜 左max<head 右min>head。四个条件都成立才是搜索二叉树
// 要的信息:左是否是搜索二叉树,最大值。 右是否是搜索二叉树 ,最小值。
// 递归返回值为 是否是搜索二叉树,最大值,最小值,要把左右要求的信息弄成合集。
public static ReturnData IsBST(Node head){
if(head == null){
return null;
}
// 左树返回值
ReturnData leftReturn = IsBST(head.left);
// 右树返回值
ReturnData rightReturn = IsBST(head.right);
// 自己也要有返回值
int min = head.value;
int max = head.value;
// 设置自己min max
if(leftReturn != null){
min = Math.min(min,leftReturn.min);
max = Math.max(max, leftReturn.max);
}
if(rightReturn != null){
min = Math.min(min,rightReturn.min);
max = Math.max(max,rightReturn.max);
}
boolean isBST = true;
// 左树最大值大于头值 false
// 左边必定达标,只有两边都达标才是false
if(leftReturn !=null && ( !leftReturn.isBST || leftReturn.max >= head.value)){
isBST = false;
}
// 右树最小值小于头值 false
if(rightReturn !=null && (!rightReturn.isBST || rightReturn.min <= head.value)){
isBST = false;
}
return new ReturnData(max,min,isBST);
}