Skip to content

Commit d18d1f0

Browse files
committed
Binary Tree Maximum Path Sum Solution
1 parent 02a83d5 commit d18d1f0

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public:
3+
int dfs(TreeNode* root, int& result){
4+
if(root == nullptr)
5+
return 0;
6+
7+
int left = max(0, dfs(root->left, result));
8+
int right = max(0, dfs(root->right, result));
9+
int sum = root->val + left + right;
10+
11+
result = max(result, sum);
12+
13+
return root->val + max(left, right);
14+
}
15+
16+
int maxPathSum(TreeNode* root) {
17+
int result = INT_MIN;
18+
19+
dfs(root, result);
20+
return result;
21+
}
22+
};

0 commit comments

Comments
 (0)