Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Example:
Input: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
思路:buttom-up,自底向上传递信息,一个是min,一个max,另外一个是是否是bst,result的信息用一个array来保存,这样在遍历整个树的过程中,已经更新了valid bst的个数。这样就是O(n)的复杂度。记住初始值用Long型表达,防止溢出。首先明白了需要自底向上传递信息,那么肯定要建立一个新的数据结构来表达这种信息,然后要明白的是,traverse这个tree还是用原来的TreeNode,但是返回的信息,是自己定义的,就跟int boolean一个道理,所以,这个建立的node跟原来的TreeNode是两个不相关的概念。每走一层,就是建立一个这样的信息节点,然后往上返回。同时,更新res array的信息。这样最后我可以搜刮到关于这个树的信息。也就是最大的BST node数目。
注意:空的节点,需要设置isBST为true;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private class Node {
public long min;
public long max;
public boolean isBST;
public int size;
public Node() {
this.min = Long.MAX_VALUE;
this.max = Long.MIN_VALUE;
this.isBST = false;
this.size = 0;
}
}
public int largestBSTSubtree(TreeNode root) {
if(root == null) {
return 0;
}
int[] res = {0};
dfs(root, res);
return res[0];
}
private Node dfs(TreeNode root, int[] res) {
Node node = new Node();
if(root == null) {
node.isBST = true; // 这个很关键,空的也是valid,这样计算leaf的时候才能正确计算;
return node;
}
Node left = dfs(root.left, res);
Node right = dfs(root.right, res);
if(left.isBST && left.max < root.val && right.isBST && right.min > root.val) {
node.isBST = true;
node.min = Math.min(left.min, root.val);
node.max = Math.max(right.max, root.val);
node.size = left.size + right.size + 1;
res[0] = Math.max(res[0], node.size);
}
return node;
}
}