-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestBSTInBinaryTree.cpp
More file actions
80 lines (67 loc) · 1.38 KB
/
LargestBSTInBinaryTree.cpp
File metadata and controls
80 lines (67 loc) · 1.38 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Node class
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = right = NULL;
}
};
// info class
class Info
{
public:
int min, max, size;
Info(int mi, int ma, int sz)
{
min = mi;
max = ma;
size = sz;
}
};
// helper function
Info helper(Node *root)
{
// base case
if (root == NULL)
{
return Info(INT_MAX, INT_MIN, 0);
}
// left sub tree call
Info left = helper(root->left);
// right sub tree call
Info right = helper(root->right);
if (root->data > left.max && root->data < right.min)
{
int currMin = min(root->data, left.min);
int currMax = max(root->data, right.max);
int currSz = left.size + right.size + 1;
return Info(currMin, currMax, currSz);
}
return Info(INT_MIN, INT_MAX, max(left.size, right.size));
}
// find size of largest BST in BT
int largestBSTinBT(Node *root)
{
Info info = helper(root);
// max BST size
return info.size;
}
int main()
{
Node *root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);
root->left->left = new Node(1);
root->left->right = new Node(8);
root->right->right = new Node(7);
cout << largestBSTinBT(root) << endl;
}