Skip to content

Commit b055420

Browse files
committed
Updated Trees
1 parent 1311806 commit b055420

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

Data Structures/Trees/BinaryTree_Maximum_Path_Sum.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 =
2424
*/
2525
class Solution {
2626
public:
27+
/**The logic is very simple. The maximum path sum will always consist of a node and its left and right sub-tree maximum path sum. As the node values can be negative also so
28+
4 cases comes here .
29+
1) A node and its both sub-trees will constitute the sum
30+
2) Only a node and its left sub-tree will constitute the sum
31+
3) Only a node and its right sub-tree will constitute the sum
32+
4) Only one node will constitute the sum
33+
*/
2734
int maxPathSum(TreeNode* root) {
2835
if(root==NULL)
2936
return 0;
@@ -41,7 +48,9 @@ class Solution {
4148
l=0;
4249
if(r<0)
4350
r=0;
51+
//Case 1 and 4 is checked here
4452
ans=max(ans,l+r+root->val);
53+
//Case 2 and 3 is checked here
4554
return max(l+root->val,r+root->val);
4655
}
4756
};

0 commit comments

Comments
 (0)