Skip to content

Commit 3f6858b

Browse files
authored
add Binary Tree Maximum Path Sum
1 parent c41980d commit 3f6858b

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

BInaryTreeMaximumPathSum.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int sum = INT_MIN;
15+
int findSum(TreeNode* root){
16+
if(root==NULL)
17+
return 0;
18+
19+
int ls = findSum(root->left);
20+
int rs = findSum(root->right);
21+
ls = max(ls,0);
22+
rs = max(rs, 0);
23+
int cs = ls + rs + root->val;
24+
sum = max(sum, cs);
25+
26+
return max(ls, rs) + root->val;
27+
28+
}
29+
int maxPathSum(TreeNode* root) {
30+
findSum(root);
31+
return sum;
32+
}
33+
};

0 commit comments

Comments
 (0)