-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathmax-path-sum-in-binary-tree.cpp
More file actions
35 lines (30 loc) · 963 Bytes
/
max-path-sum-in-binary-tree.cpp
File metadata and controls
35 lines (30 loc) · 963 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
#include <vector>
using namespace std;
class BinaryTree {
public:
int value;
BinaryTree* left;
BinaryTree* right;
BinaryTree(int value);
void insert(vector<int> values, int i = 0);
};
struct sums {
int branchSum = INT_MIN;
int runningSum = INT_MIN;
sums(int b, int r) : branchSum(b), runningSum(r) {}
};
sums findMaxPath(BinaryTree* tree) {
if (!tree) return sums(0, 0);
sums ls = findMaxPath(tree->left);
sums rs = findMaxPath(tree->right);
int maxPathBranch = max(ls.branchSum, rs.branchSum);
maxPathBranch = max(maxPathBranch + tree->value, tree->value);
int maxSumAsTriangle = max(maxPathBranch, ls.branchSum + rs.branchSum + tree->value);
int maxRunningSum = max(maxSumAsTriangle, max(ls.runningSum, rs.runningSum));
return sums(maxPathBranch, maxRunningSum);
}
int maxPathSum(BinaryTree tree) {
// Write your code here.
sums result = findMaxPath(&tree);
return result.runningSum;
}