[AlgoExpert] Max Path Sum In Binary Tree

Max Path Sum In Binary Tree

  • Time : O(n)
  • Space : O(1)
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
#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);
};

int helper(BinaryTree tree, int& res) {
int path = tree.value;
if(tree.left && tree.right) {
int l = helper(*tree.left, res);
int r = helper(*tree.right, res);
res = max({res, path, l + path, r + path, l + r + path});
return max({path, l + path, r + path, 0});
} else if(tree.left) {
int l = helper(*tree.left, res);
res = max({res, l + path, path});
return max({0, path, l + path});
} else if(tree.right) {
int r = helper(*tree.right, res);
res = max({res, r + path, path});
return max({0, path, r + path});
} else {
res = max(res, path);
return max(0,path);
}
}

int maxPathSum(BinaryTree tree) {
int res = INT_MIN;
helper(tree, res);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/max-path-sum-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.