forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
35 lines (34 loc) · 1.03 KB
/
Solution.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxSumBST(TreeNode* root) {
int ans = 0;
const int inf = 1 << 30;
function<vector<int>(TreeNode*)> dfs = [&](TreeNode* root) {
if (!root) {
return vector<int>{1, inf, -inf, 0};
}
auto l = dfs(root->left);
auto r = dfs(root->right);
int v = root->val;
if (l[0] && r[0] && l[2] < v && v < r[1]) {
int s = l[3] + r[3] + v;
ans = max(ans, s);
return vector<int>{1, min(l[1], v), max(r[2], v), s};
}
return vector<int>(4);
};
dfs(root);
return ans;
}
};