Skip to content

Commit 1311806

Browse files
committed
Added to tree
1 parent d77711e commit 1311806

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Src : LeetCode
3+
--------------
4+
5+
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
6+
The path sum of a path is the sum of the node's values in the path.
7+
Given the root of a binary tree, return the maximum path sum of any path.
8+
9+
Input: root = [-10,9,20,null,null,15,7]
10+
Output: 42
11+
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* struct TreeNode {
17+
* int val;
18+
* TreeNode *left;
19+
* TreeNode *right;
20+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
21+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
22+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
23+
* };
24+
*/
25+
class Solution {
26+
public:
27+
int maxPathSum(TreeNode* root) {
28+
if(root==NULL)
29+
return 0;
30+
int ans=root->val,sum;
31+
sum=helper(root,ans);
32+
return max(ans,sum);
33+
}
34+
35+
int helper(TreeNode* root,int &ans){
36+
if(root==NULL)
37+
return 0;
38+
int l=helper(root->left,ans);
39+
int r=helper(root->right,ans);
40+
if(l<0)
41+
l=0;
42+
if(r<0)
43+
r=0;
44+
ans=max(ans,l+r+root->val);
45+
return max(l+root->val,r+root->val);
46+
}
47+
};

0 commit comments

Comments
 (0)