# 124. Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

# Solution

Approach 1: once we know the maximum sum of each node (node itself and a simple path down its subtree, no turns) in the tree, the max path sum can be found recursively from 3 cases: when the result passes the root node, when the result is in the right subtree only, when the result is in the left subtree only. Time: O(N).

# Code (Python)

Approach 1:

class Solution:
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self._max_path_sum(root, {root: root.val, None: 0})
    
    def _max_path_sum(self, root, cache):
        if not root:
            return 0
        # when result passes the root node
        result = root.val + max(0, self._max_sum_from_root(root.left, cache)) + max(0, self._max_sum_from_root(root.right, cache))
        # when result is in the left subtree
        if root.left:
            result = max(result, self._max_path_sum(root.left, cache))
        # when result is in the right subtree
        if root.right:
            result = max(result, self._max_path_sum(root.right, cache))
        return result
    
    def _max_sum_from_root(self, root, cache): # the cache stores _max_sum_from_root() for each node
        # calculate the maximum sum of each node (node itself and a simple path down its subtree, no turns)
        if not root:
            return 0
        if root.left not in cache:
            cache[root.left] = self._max_sum_from_root(root.left, cache)
        if root.right not in cache:
            cache[root.right] = self._max_sum_from_root(root.right, cache)
        # 0 needs to be compared also because values can be negative
        return max(cache[root.left], cache[root.right], 0) + root.val

# Code (C++)

Approach 1:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int maxPath;
    int doMaxPathSum(TreeNode* root) {
        if (root == NULL)
            return 0;
        int left = doMaxPathSum(root->left);
        int right = doMaxPathSum(root->right);
        int res = root->val;
        if (left > 0 || right > 0)
            res += std::max(left, right);
        maxPath = std::max(maxPath, res);
        if (left > 0 && right > 0)
            maxPath = std::max(maxPath, left + right + root->val);
        return res;
    }
public:
    int maxPathSum(TreeNode* root) {
        maxPath = INT_MIN;
        doMaxPathSum(root);
        return maxPath;
    }
};