|
| 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 | + /**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 | + */ |
| 34 | + int maxPathSum(TreeNode* root) { |
| 35 | + if(root==NULL) |
| 36 | + return 0; |
| 37 | + int ans=root->val,sum; |
| 38 | + sum=helper(root,ans); |
| 39 | + return max(ans,sum); |
| 40 | + } |
| 41 | + |
| 42 | + int helper(TreeNode* root,int &ans){ |
| 43 | + if(root==NULL) |
| 44 | + return 0; |
| 45 | + int l=helper(root->left,ans); |
| 46 | + int r=helper(root->right,ans); |
| 47 | + if(l<0) |
| 48 | + l=0; |
| 49 | + if(r<0) |
| 50 | + r=0; |
| 51 | + //Case 1 and 4 is checked here |
| 52 | + ans=max(ans,l+r+root->val); |
| 53 | + //Case 2 and 3 is checked here |
| 54 | + return max(l+root->val,r+root->val); |
| 55 | + } |
| 56 | +}; |
0 commit comments