> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Binary Tree Maximum Path Sum Python Solution

> Tested Python solution for LeetCode 124 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 124, Hard. Topics: Dynamic Programming, Tree, Depth-First Search, Binary Tree. [View on LeetCode](https://leetcode.com/problems/binary-tree-maximum-path-sum/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 124   # by problem number
lcpy gen -s binary_tree_maximum_path_sum   # by problem name
```

## Problem

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.

The **path sum** of a path is the sum of the node's values in the path.

Given the `root` of a binary tree, return *the maximum **path sum** of any **non-empty** path*.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg)

```
Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
```

![Example 2](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg)

```
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
```

### Constraints

* The number of nodes in the tree is in the range \[1, 3 \* 10^4].
* -1000 \<= Node.val \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_tree_maximum_path_sum/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_tree_maximum_path_sum/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n) where n is the number of nodes
    # Space: O(h) where h is the height of the tree (recursion stack)
    def max_path_sum(self, root: TreeNode[int] | None) -> int:
        """
        Find the maximum path sum in a binary tree.

        A path is a sequence of nodes where each pair of adjacent nodes
        has an edge connecting them. A node can only appear once in the path.
        The path doesn't need to pass through the root.

        Uses DFS with post-order traversal to calculate:
        1. Maximum path sum that can be extended upward from current node
        2. Maximum path sum that includes current node as the highest point
        """
        if not root:
            return 0

        max_sum = float("-inf")

        def dfs(node: TreeNode[int] | None) -> int:
            nonlocal max_sum

            if not node:
                return 0

            # Get maximum path sum from left and right subtrees
            # If negative, we don't include them (take 0 instead)
            left_max = max(0, dfs(node.left))
            right_max = max(0, dfs(node.right))

            # Current path sum if this node is the highest point
            # (left path + current node + right path)
            current_path_sum = node.val + left_max + right_max

            # Update global maximum
            max_sum = max(max_sum, current_path_sum)

            # Return maximum path sum that can be extended upward
            # (either left or right path + current node)
            return node.val + max(left_max, right_max)

        dfs(root)
        return int(max_sum)
```

## Complexity

| Time                                | Space                                                    |
| ----------------------------------- | -------------------------------------------------------- |
| O(n) where n is the number of nodes | O(h) where h is the height of the tree (recursion stack) |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
