-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path1373.cpp
33 lines (30 loc) · 826 Bytes
/
1373.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
class Solution
{
public:
int maxSumBST(TreeNode* root)
{
dfs(root);
return maxv;
}
private:
int maxv = 0;
pair<int, int> dfs(TreeNode* root)
{
if (root == nullptr) return {true, 0};
pair<int, int> res = {true, root->val};
if (root->left != nullptr)
{
auto left = dfs(root->left);
if (left.first && root->left->val < root->val) res.second += left.second;
else res.first = false;
}
if (root->right != nullptr)
{
auto right = dfs(root->right);
if (right.first && root->right->val > root->val) res.second += right.second;
else res.first = false;
}
if (res.first) maxv = max(maxv, res.second);
return res;
}
};