Skip to content

Commit 657f171

Browse files
authored
Create main.cpp
1 parent b688064 commit 657f171

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
13+
class nodeInfo{
14+
public:
15+
int mini;
16+
int maxi;
17+
bool isBST;
18+
int size;
19+
int sum;
20+
};
21+
class Solution {
22+
public:
23+
nodeInfo getLargestBSTSize(TreeNode* root, int &ans){
24+
if(root == NULL) return nodeInfo{INT_MAX, INT_MIN, true, 0, 0};
25+
26+
nodeInfo left = getLargestBSTSize(root -> left, ans);
27+
nodeInfo right = getLargestBSTSize(root -> right, ans);
28+
29+
nodeInfo currentNode;
30+
currentNode.size = left.size + right.size + 1;
31+
currentNode.sum = left.sum + right.sum + root -> val;
32+
currentNode.mini = min(root -> val, left.mini);
33+
currentNode.maxi = max(root -> val, right.maxi);
34+
35+
if(left.isBST && right.isBST && (root -> val > left.maxi && root -> val < right.mini)){
36+
currentNode.isBST = true;
37+
ans = max(ans, currentNode.sum);
38+
}else{
39+
currentNode.isBST = false;
40+
}
41+
42+
return currentNode;
43+
}
44+
45+
int maxSumBST(TreeNode* root) {
46+
int max_sum = 0;
47+
getLargestBSTSize(root, max_sum);
48+
return max_sum;
49+
}
50+
};

0 commit comments

Comments
 (0)