-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSize_of_largest_bst.cpp
52 lines (44 loc) · 952 Bytes
/
Size_of_largest_bst.cpp
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
#include <bits/stdc++.h>
class info
{
public:
int maxi;
int mini;
bool isBST;
int size;
};
info solve(TreeNode<int> *root, int &ans)
{
// base case
if (root == NULL)
{
return {INT_MIN, INT_MAX, true, 0};
}
info left = solve(root->left, ans);
info right = solve(root->right, ans);
info currNode;
currNode.size = left.size + right.size + 1;
currNode.maxi = max(root->data, right.maxi);
currNode.mini = min(root->data, left.mini);
if (left.isBST && right.isBST && (root->data > left.maxi && root->data < right.mini))
{
currNode.isBST = true;
}
else
{
currNode.isBST = false;
}
// answer update
if (currNode.isBST)
{
ans = max(ans, currNode.size);
}
return currNode;
}
int largestBST(TreeNode<int> *root)
{
// Write your code here.
int maxSize = 0;
info temp = solve(root, maxSize);
return maxSize;
}