/**
* 返回二叉树中最大的二叉搜索子树的大小
* <p>
* 二叉搜索子树:
* 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
* 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
* 它的左、右子树也分别为二叉排序树
*/
public class MaxSubBSTSize {
public static int maxSubBSTSize(Node head) {
if (head == null) {
return 0;
}
return process(head).maxSubBSTSize;
}
public static ResultInfo process(Node node) {
if (node == null) {
return null;
}
ResultInfo leftInfo = process(node.left);
ResultInfo rightInfo = process(node.right);
int min = node.value;
int max = node.value;
int maxSubBSTSize = 0;
if (leftInfo != null) {
min = Math.min(min, leftInfo.min);
max = Math.max(max, leftInfo.max);
maxSubBSTSize = Math.max(maxSubBSTSize, leftInfo.maxSubBSTSize);
}
if (rightInfo != null) {
min = Math.min(min, rightInfo.min);
max = Math.max(max, rightInfo.max);
maxSubBSTSize = Math.max(maxSubBSTSize, rightInfo.maxSubBSTSize);
}
boolean isBST = false;
if ((leftInfo == null ? true : (leftInfo.isAllBST && leftInfo.max < node.value))
&& (rightInfo == null ? true : (rightInfo.isAllBST && rightInfo.min > node.value))) {
isBST = true;
maxSubBSTSize = (leftInfo == null ? 0 : leftInfo.maxSubBSTSize) + (rightInfo == null ? 0 : rightInfo.maxSubBSTSize) + 1;
}
return new ResultInfo(isBST, maxSubBSTSize, min, max);
}
/**
* 向左右子树索要信息
*/
public static class ResultInfo {
// 是否是二叉搜索子树
public boolean isAllBST;
// 最大二叉搜索子树的大小
public int maxSubBSTSize;
public int min;
public int max;
public ResultInfo(boolean is, int size, int mi, int ma) {
isAllBST = is;
maxSubBSTSize = size;
min = mi;
max = ma;
}
}
/**
* 二叉树结构
*/
public static class Node {
// 节点值
private int value;
public Node left;
public Node right;
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */