-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-maximum-path-sum(AC).cpp
More file actions
58 lines (53 loc) · 1.41 KB
/
Copy pathbinary-tree-maximum-path-sum(AC).cpp
File metadata and controls
58 lines (53 loc) · 1.41 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
// 1WA, 1AC, recursive solution in O(n) time.
#include <algorithm>
#include <climits>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
max_val = INT_MIN;
maxPathSumRecursive(root);
return max_val;
}
private:
int max_val;
// return the maximum root-to-leaf sum, the 'root' refers to the current node as the root.
int maxPathSumRecursive(TreeNode *root) {
if (root == nullptr) {
return 0;
}
// the root-to-leaf sum
int sum_single;
// the leaf-to-leaf or root-to-leaf sum
int sum_double;
int max1 = 0, max2 = 0;
sum_double = sum_single = root->val;
if (root->left != nullptr) {
max1 = maxPathSumRecursive(root->left);
if (max1 < 0) {
max1 = 0;
}
}
if (root->right != nullptr) {
max2 = maxPathSumRecursive(root->right);
if (max2 < 0) {
max2 = 0;
}
}
sum_single += max(max1, max2);
sum_double += max1 + max2;
if (sum_double > max_val) {
max_val = sum_double;
}
return sum_single;
}
};