与其明天开始,不如现在行动!
文章目录
- 最大二叉搜索树
- 💎总结
最大二叉搜索树
题目
给定一颗二叉树的头节点head,返回这颗二叉树中最大的二叉搜索子树的节点数量
搜索二叉树:整棵树上没有重复值,左树的值都比节点小,右树的值都比节点大
举例
下图中最大的二叉搜索树头节点:7,节点数量:2
分析
- 和头节点有关:整棵树都是二叉搜索树
- 和头节点无关:最大二叉搜索子树在左树上或者右树上
- 需要的信息
- 每棵树是否是二叉搜索树
- 最大搜索二叉树的节点数量
- 每棵树的最大节点值
- 每棵树的最小节点值
代码
public class MaxSubBSTNode {
public static class Node {
public int val;
public Node left;
public Node right;
public Node(int val) {
this.val = val;
}
}
public static class Info {
public boolean isAllBST;
public int maxBSTSize;
public int max;
public int min;
public Info(boolean isAllBST, int maxBSTSize, int max, int min) {
this.isAllBST = isAllBST;
this.maxBSTSize = maxBSTSize;
this.max = max;
this.min = min;
}
}
public static int getMaxSubBSTNode(Node head) {
if (head == null) {
return 0;
}
return BSTNodeProcess(head).maxBSTSize;
}
private static Info BSTNodeProcess(Node head) {
if (head == null) {
return null;
}
Info leftInfo = BSTNodeProcess(head.left);
Info rightInfo = BSTNodeProcess(head.right);
int min = head.val;
int max = head.val;
int maxBSTSize = 0;
if (leftInfo != null) {
min = Math.min(leftInfo.min, min);
max = Math.max(leftInfo.max, max);
maxBSTSize = Math.max(maxBSTSize, leftInfo.maxBSTSize);
}
if (rightInfo != null) {
min = Math.min(rightInfo.min, min);
max = Math.max(rightInfo.max, max);
maxBSTSize = Math.max(maxBSTSize, rightInfo.maxBSTSize);
}
boolean leftIsBST = leftInfo == null || leftInfo.isAllBST;
boolean rightIsBST = rightInfo == null || rightInfo.isAllBST;
boolean leftIsBigger = leftInfo == null || leftInfo.max < head.val;
boolean rightIsBigger = rightInfo == null || rightInfo.min > head.val;
boolean isAllBST = false;
if (leftIsBST && rightIsBST && leftIsBigger && rightIsBigger) {
maxBSTSize = (leftInfo == null ? 0 : leftInfo.maxBSTSize)
+
(rightInfo == null ? 0 : rightInfo.maxBSTSize)
+
1;
isAllBST = true;
}
return new Info(isAllBST, maxBSTSize, max, min);
}
public static void main(String[] args) {
Node head = new Node(4);
head.left = new Node(2);
head.right = new Node(6);
head.left.left = new Node(1);
head.left.right = new Node(3);
head.right.left = new Node(5);
head.right.right = new Node(3);
System.out.println(getMaxSubBSTNode(head));
}
}
💎总结
本文中若是有出现的错误请在评论区或者私信指出,我再进行改正优化,如果文章对你有所帮助,请给博主一个宝贵的三连,感谢大家😘!!!