-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 174.java
More file actions
43 lines (34 loc) · 1.04 KB
/
Day 174.java
File metadata and controls
43 lines (34 loc) · 1.04 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
class Solution {
static class Info {
boolean isBST;
int size;
int min;
int max;
Info(boolean isBST, int size, int min, int max) {
this.isBST = isBST;
this.size = size;
this.min = min;
this.max = max;
}
}
static int largestBst(Node root) {
return solve(root).size;
}
static Info solve(Node root) {
if (root == null) {
return new Info(true, 0, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
Info left = solve(root.left);
Info right = solve(root.right);
if (left.isBST && right.isBST &&
root.data > left.max && root.data < right.min) {
int size = left.size + right.size + 1;
int min = Math.min(root.data, left.min);
int max = Math.max(root.data, right.max);
return new Info(true, size, min, max);
}
return new Info(false,
Math.max(left.size, right.size),
0, 0);
}
}