Skip to content

Commit 83d8ca1

Browse files
authored
added maximum path sum (#28)
1 parent bfe9506 commit 83d8ca1

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

C++/Binary-Tree-Maximum-Path-Sum.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
* Runtime : 40ms
13+
* Memory : 28.5 MB
14+
*
15+
*
16+
*/
17+
class Solution {
18+
public:
19+
20+
int solve(TreeNode* root, int &ans)
21+
{
22+
if(root == NULL)
23+
return 0;
24+
25+
# to traverse left and right childs
26+
int l = solve(root->left, ans);
27+
int r = solve(root->right, ans);
28+
29+
/* to find max sum including root_val and left and child subtree
30+
max sum or just including root val if result from subtree is - negative
31+
*/
32+
int temp = max(max(l,r)+root->val, root->val);
33+
34+
/* in case max sum does not include main root and
35+
forms maximum sum path through sub tree
36+
*/
37+
int res = max(temp, root->val+l+r);
38+
ans = max(res,ans);
39+
return temp;
40+
}
41+
int maxPathSum(TreeNode* root) {
42+
int ans = INT_MIN;
43+
solve(root,ans);
44+
return ans;
45+
46+
}
47+
};

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
147147
| 129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | [Java](./Java/sum-root-to-leaf-numbers.java) | _O(n)_ | _O(logn)_ | Medium | Binary Tree, Depth First Search | |
148148
| 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | [Java](./Java/Range-Sum-Query-Mutable.java) | _O(logn)_ | _O(n)_ | Medium | Segment Tree | |
149149
| 919 | [Complete Binary Tree Inserter](https://leetcode.com/problems/complete-binary-tree-inserter/) | [Java](./Java/complete-binary-tree-inserter.java) | _O(n)_ | _O(n)_ | Medium | Tree | |
150+
| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [C++](./C++/Binary-Tree-Maximum-Path-Sum.cpp) | _O(n)_ | _O(n)_ | Hard | Tree | |
151+
150152

151153
<br/>
152154
<div align="right">

0 commit comments

Comments
 (0)