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