-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathmaximum-sum-bst-in-binary-tree.cpp
78 lines (74 loc) · 2.5 KB
/
maximum-sum-bst-in-binary-tree.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// dfs solution with stack
class Solution {
public:
int maxSumBST(TreeNode* root) {
using RET = tuple<bool, int, int, int>;
int result = 0;
RET ret;
vector<tuple<TreeNode*, shared_ptr<vector<RET>>, RET *>> stk = {{root, nullptr, &ret}};
while (!stk.empty()) {
const auto [node, tmp, ret] = stk.back(); stk.pop_back();
if (tmp) {
const auto& [lvalid, lsum, lmin, lmax] = (*tmp)[0];
const auto& [rvalid, rsum, rmin, rmax] = (*tmp)[1];
if (lvalid && rvalid && lmax < node->val && node->val < rmin) {
const auto& total = lsum + node->val + rsum;
result = max(result, total);
*ret = {true, total, min(lmin, node->val), max(node->val, rmax)};
continue;
}
*ret = {false, 0, 0, 0};
continue;
}
if (!node) {
*ret = {true, 0,
numeric_limits<int>::max(),
numeric_limits<int>::min()};
continue;
}
const auto& new_tmp = make_shared<vector<RET>>(2);
stk.emplace_back(node, new_tmp, ret);
stk.emplace_back(node->right, nullptr, &((*new_tmp)[1]));
stk.emplace_back(node->left, nullptr, &((*new_tmp)[0]));
}
return result;
}
};
// Time: O(n)
// Space: O(h)
// dfs solution with recursion
class Solution2 {
public:
int maxSumBST(TreeNode* root) {
int result = 0;
dfs(root, &result);
return result;
}
private:
tuple<bool, int, int, int> dfs(TreeNode *node, int *result) {
if (!node) {
return {true, 0,
numeric_limits<int>::max(),
numeric_limits<int>::min()};
}
const auto& [lvalid, lsum, lmin, lmax] = dfs(node->left, result);
const auto& [rvalid, rsum, rmin, rmax] = dfs(node->right, result);
if (lvalid && rvalid && lmax < node->val && node->val < rmin) {
const auto& total = lsum + node->val + rsum;
*result = max(*result, total);
return {true, total, min(lmin, node->val), max(node->val, rmax)};
}
return {false, 0, 0, 0};
}
};