-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestBSTInTree.java
More file actions
48 lines (35 loc) · 1.21 KB
/
LargestBSTInTree.java
File metadata and controls
48 lines (35 loc) · 1.21 KB
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
package BinarySearchTrees;
public class LargestBSTInTree {
static int MAX = Integer.MAX_VALUE;
static int MIN = Integer.MIN_VALUE;
static NodeInfo largestBST(Node root) {
if (root == null) {
return new NodeInfo(0, MIN, MAX, true);
}
NodeInfo left = largestBST(root.left);
NodeInfo right = largestBST(root.right);
NodeInfo returnInfo = new NodeInfo();
returnInfo.min = Math.min(left.min, root.val);
returnInfo.max = Math.max(right.max, root.val);
// Crazy Stuff.
returnInfo.isBST = left.isBST && right.isBST && root.val > left.max && root.val < right.min;
if (returnInfo.isBST) returnInfo.size = left.size + right.size + 1;
else returnInfo.size = Math.max(left.size, right.size);
return returnInfo;
}
static int largestBst(Node root) {
return largestBST(root).size;
}
static class NodeInfo {
int size; int max;
int min; boolean isBST;
NodeInfo() {
}
NodeInfo(int size, int max, int min, boolean isBST) {
this.size = size;
this.max = max;
this.min = min;
this.isBST = isBST;
}
}
}