File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
18 - Binary Search Tree Data Structure Problems/18 - Largest BST Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ class info {
2+ public:
3+ int mini;
4+ int maxi;
5+ bool isBST;
6+ int size;
7+ };
8+
9+ class Solution {
10+ public:
11+ info getLargestBSTInfo (Node* root, int &ans) {
12+ if (root == NULL ) return info{INT_MAX, INT_MIN, true , 0 };
13+
14+ info left = getLargestBSTInfo (root->left , ans);
15+ info right = getLargestBSTInfo (root->right , ans);
16+
17+ info currNode;
18+ currNode.size = left.size + right.size + 1 ;
19+ currNode.maxi = max (root->data , right.maxi );
20+ currNode.mini = min (root->data , left.mini );
21+
22+ if (left.isBST && right.isBST && (root->data > left.maxi && root->data < right.mini )) {
23+ currNode.isBST = true ;
24+ } else {
25+ currNode.isBST = false ;
26+ }
27+
28+ if (currNode.isBST ) ans = max (ans, currNode.size );
29+
30+ return currNode;
31+ }
32+
33+ int largestBst (Node* root) {
34+ int maxSize = 0 ;
35+ getLargestBSTInfo (root, maxSize);
36+ return maxSize;
37+ }
38+ };
You can’t perform that action at this time.
0 commit comments