-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
52 lines (44 loc) · 1.14 KB
/
Copy pathsolution.cpp
File metadata and controls
52 lines (44 loc) · 1.14 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
48
49
50
51
52
class Info {
public:
int size, minVal, maxVal;
bool isBST;
Info(int s, int minV, int maxV, bool bst) {
size = s;
minVal = minV;
maxVal = maxV;
isBST = bst;
}
};
class Solution {
public:
Info solve(Node* root) {
// Base case
if (!root)
return Info(0, INT_MAX, INT_MIN, true);
// Left & Right subtree info
Info left = solve(root->left);
Info right = solve(root->right);
// Check BST condition
if (left.isBST && right.isBST &&
root->data > left.maxVal &&
root->data < right.minVal) {
// Current subtree is BST
return Info(
left.size + right.size + 1,
min(root->data, left.minVal),
max(root->data, right.maxVal),
true
);
}
// Not a BST
return Info(
max(left.size, right.size),
INT_MIN,
INT_MAX,
false
);
}
int largestBst(Node *root) {
return solve(root).size;
}
};