Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- int maxSum = INT_MIN;
- int maxPathSum(TreeNode* root) {
- dfs(root);
- return maxSum;
- }
- int dfs(TreeNode *root){
- if(!root) return 0;
- int leftSum = 0, rightSum = 0, curSum = root->val;
- // Get the left subtree sum or 0 if negative.
- if(root->left)
- leftSum = max(leftSum, dfs(root->left));
- // Get the right subtree sum or 0 if negative.
- if(root->right)
- rightSum = max(rightSum, dfs(root->right));
- // Update answer.
- maxSum = max(maxSum, curSum+leftSum+rightSum);
- return max(leftSum+curSum, rightSum+curSum);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment