333. Largest BST Subtree

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.
Here’s an example:

1
2
3
4
5
10
/ \
5 15
/ \ \
1 8 7

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?

解法1:

C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class NodeInfo {
boolean isBST;
int count;
int max;
int min;
public NodeInfo (boolean isBST, int count, int max, int min) {
this.isBST = isBST;
this.count = count;
this.max = max;
this.min = min;
}
};
int res = 0; // Store the final result
public int largestBSTSubtree(TreeNode root) {
if (root == null) {
return 0;
}
NodeInfo dummy = helper(root);
return res;
}
private NodeInfo helper(TreeNode root) {
if (root == null) {
return new NodeInfo(true, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
NodeInfo left = helper(root.left);
NodeInfo right = helper(root.right);
boolean isBST = false;
if (root.val > left.max && root.val < right.min) {
isBST = left.isBST && right.isBST;
}
int count = left.count + right.count + 1;
if (isBST) {
res = Math.max(res, count);
}
int max = Math.max(left.max, Math.max(right.max, root.val));
int min = Math.min(left.min, Math.min(right.min, root.val));
return new NodeInfo(isBST, count, max, min);
}
}