-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path124_binary_tree_maximum_path_sum.cpp
More file actions
63 lines (53 loc) · 2.16 KB
/
124_binary_tree_maximum_path_sum.cpp
File metadata and controls
63 lines (53 loc) · 2.16 KB
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
/**
* 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 maxPathSum(TreeNode* root) {
// list of nodes, level order from the root
vector<TreeNode*> nodes_vector;
// hashmap of maximum downward sum from a node
unordered_map<TreeNode*, int> max_down_map;
if (!root)
return 0;
nodes_vector.push_back(root);
// populate the list of nodes
for (size_t i = 0; i < nodes_vector.size(); ++i) {
auto node = nodes_vector[i];
if (node->left) nodes_vector.push_back(node->left);
if (node->right) nodes_vector.push_back(node->right);
}
int best_path_sum = INT_MIN;
max_down_map.reserve(nodes_vector.size());
max_down_map[nullptr] = 0;
for (int i = nodes_vector.size() - 1; i >= 0; --i) {
auto node = nodes_vector[i];
// maximum downward contribution a node can give to it's parent
int max_down;
// maximum path sum through the node (candidate best path sum)
// (the path that uses this node as highest point)
int through_sum;
int left_down = max_down_map[node->left];
int right_down = max_down_map[node->right];
left_down = max(left_down, 0);
right_down = max(right_down, 0);
max_down = node->val + max(left_down, right_down);
through_sum = node->val + left_down + right_down;
max_down_map[node] = max_down;
best_path_sum = max(best_path_sum, through_sum);
}
return best_path_sum;
}
};
// NOTE: this algorithm is sub-optimal and can be further improved.
// While complexity is already O(n), a solution based on post-order
// traversal avoids the overhead of a hashtable and allows to find
// the maximum path sum in one scan.