Skip to content

Commit 0621388

Browse files
committed
Create Binary Tree Maximum Path Sum.cpp
1 parent 387769f commit 0621388

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Binary Tree Maximum Path Sum.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int ans;
13+
int dfs(TreeNode *r)
14+
{
15+
int mx=0,x=r->val;
16+
if (r->left)
17+
{
18+
int z=dfs(r->left);
19+
mx=max(mx,z);
20+
x+=z;
21+
}
22+
if (r->right)
23+
{
24+
int z=dfs(r->right);
25+
mx=max(mx,z);
26+
x+=z;
27+
}
28+
ans=max(ans,r->val+mx);
29+
ans=max(ans,x);
30+
return r->val+mx;
31+
}
32+
int maxPathSum(TreeNode *root) {
33+
// Start typing your C/C++ solution below
34+
// DO NOT write int main() function
35+
if (!root)return 0;
36+
ans=root->val;
37+
dfs(root);
38+
return ans;
39+
}
40+
};

0 commit comments

Comments
 (0)