-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_path_sum_ii.cpp
More file actions
58 lines (46 loc) · 1.14 KB
/
Copy pathbinary_tree_path_sum_ii.cpp
File metadata and controls
58 lines (46 loc) · 1.14 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
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree.
* @return an integer
*/
int maxPathSum2(TreeNode *root) {
// Write your code here
if (root == NULL) {
return 0;
}
vector<int> path;
int result = helper(root, path);
if (path.size() == 0) {
return root->val;
}
return result;
}
int helper(TreeNode *node, vector<int> &path) {
if (node == NULL) {
return 0;
}
int max_left = helper(node->left, path);
int max_right = helper(node->right, path);
int m_max = max(max_left, max_right);
m_max += node->val;
if (m_max >= 0) {
path.push_back(node->val);
} else {
path.clear();
}
return max(0, m_max);
}
};