---
# System prepended metadata

title: 'Leetcode : 0124. Binary Tree Maximum Path Sum (Tree)'
tags: [leetcode]

---

# Leetcode : 0124. Binary Tree Maximum Path Sum (Tree)
###### tags:`leetcode`

```
/**
 * 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 maxPathSum(TreeNode* root) {
        int ans = INT_MIN;
        DFSFindMax(root, ans);
        return ans;
    }
    int DFSFindMax(TreeNode* root,int &ans){
        if(!root) return 0;

        int leftmax = max(0,DFSFindMax(root->left,ans)); 
        //zero is lower return is negative number become 0
        int rightmax = max(0,DFSFindMax(root->right,ans));
        //zero is lower return is negative number become 0
 
        ans = max(ans , leftmax + rightmax + root->val);
        // total and now max compare how is high.

        return max(leftmax,rightmax) + root->val; //return self and max (left or right)
    }
};
```