题目:
给定一棵二叉树的头节点head,返回这颗树中最大的搜索二叉子树的大小
1、解决方案1
1.1、思路:
从head节点开始判断,如果以该节点为头的树是二叉搜索树,那么直接返回大小。否则就继续判断该节点的左右子树(左右子树中取最大值)
1.2、代码:
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
//如果是二叉搜索树,则返回大小。否则返回0
public static int getBSTSize(Node head) {
if (head == null) {
return 0;
}
ArrayList<Node> arr = new ArrayList<>();
in(head, arr);
//中序遍历之后,得到集合arr,然后遍历arr
//如果该树是二叉搜索树,那么一定满足索引i位置元素一定是大于索引(i-1)位置的元素值
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i).value <= arr.get(i - 1).value) {
return 0;
}
}
return arr.size();
}
//中序遍历该树,然后把遍历到的数据都加入到集合中
public static void in(Node head, ArrayList<Node> arr) {
if (head == null) {
return;
}
in(head.left, arr);
arr.add(head);
in(head.right, arr);
}
//方案1:
public static int maxSubBSTSize1(Node head) {
if (head == null) {
return 0;
}
//如果以head为头节点的树是二叉搜索树,则返回大小。否则返回0
int h = getBSTSize(head);
//如果不为0,说明以head为头的子树是二叉搜索树
if (h != 0) {
return h;
}
//如果以head为头的子树不是二叉搜索树,那么就看看其左右子树是不是二叉搜索树
return Math.max(maxSubBSTSize1(head.left), maxSubBSTSize1(head.right));
}
2、解决方案2
2.1、思路:
1、向左右子树分别要信息
2、返回左子树是不是二叉搜索树,如果是二叉搜索树,那么此时的二叉搜索树的大小是多少。以及此树上最大、最小值
3、返回右子树是不是二叉搜索树,如果是二叉搜索树,那么此时的二叉搜索树的大小是多少。以及此树上最大、最小值
4、最后根据信息来判断
2.2、代码:
//方案2:
public static int maxSubBSTSize2(Node head) {
if (head == null) {
return 0;
}
return process(head).maxSubBSTSize;
}
public static class Info {
//以该节点为头的子树是不是二叉搜索树
public boolean isBST;
//如果是二叉搜索树,那么此时的二叉搜索树的大小是多少
public int maxSubBSTSize;
public int min;
public int max;
public Info(boolean is, int size, int mi, int ma) {
isBST = is;
maxSubBSTSize = size;
min = mi;
max = ma;
}
}
public static Info process(Node head) {
if (head == null) {
return null;
}
//当前节点左子树信息
Info leftInfo = process(head.left);
//当前节点右子树信息
Info rightInfo = process(head.right);
int min = head.value;
int max = head.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.isBST && leftInfo.max < head.value))
&&
(rightInfo == null ? true : (rightInfo.isBST && rightInfo.min > head.value))
) {
//此时以head为头的子树是二叉搜索树
isBST = true;
//此时大小为:左子树大小 + 右子树大小
maxSubBSTSize = (leftInfo == null ? 0 : leftInfo.maxSubBSTSize)
+ (rightInfo == null ? 0 : rightInfo.maxSubBSTSize) + 1;
}
return new Info(isBST, maxSubBSTSize, min, max);
}