nikunjsoni

124

May 6th, 2021
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  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. class Solution {
  13. public:
  14.     int maxSum = INT_MIN;
  15.     int maxPathSum(TreeNode* root) {
  16.         dfs(root);
  17.         return maxSum;
  18.     }
  19.    
  20.     int dfs(TreeNode *root){
  21.         if(!root) return 0;
  22.         int leftSum = 0, rightSum = 0, curSum = root->val;
  23.        
  24.         // Get the left subtree sum or 0 if negative.
  25.         if(root->left)
  26.             leftSum = max(leftSum, dfs(root->left));
  27.         // Get the right subtree sum or 0 if negative.
  28.         if(root->right)
  29.             rightSum = max(rightSum, dfs(root->right));
  30.        
  31.         // Update answer.
  32.         maxSum = max(maxSum, curSum+leftSum+rightSum);
  33.         return max(leftSum+curSum, rightSum+curSum);
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment