-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1373.cpp
More file actions
executable file
·40 lines (35 loc) · 818 Bytes
/
LC1373.cpp
File metadata and controls
executable file
·40 lines (35 loc) · 818 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/
*/
class Solution {
private:
int max_sum = 0;
struct Node {
bool valid;
int sum, min, max;
Node(TreeNode* node) : sum(node->val), min(node->val), max(node->val), valid(true) {}
};
public:
Node get_sum(TreeNode* node) {
Node curr(node);
if (node->left) {
Node left = get_sum(node->left);
curr.min = left.min;
curr.sum += left.sum;
curr.valid &= (left.max < node->val && left.valid);
}
if (node->right) {
Node right = get_sum(node->right);
curr.max = right.max;
curr.sum += right.sum;
curr.valid &= (right.min > node->val && right.valid);
}
if (curr.valid)
max_sum = max(curr.sum, max_sum);
return curr;
}
int maxSumBST(TreeNode* root) {
get_sum(root);
return max_sum;
}
};