> ## 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.

# Longest Univalue Path Python Solution

> Tested Python solution for LeetCode 687 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 687, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree), [Dynamic Programming](/catalog/topics/dynamic-programming). [View on LeetCode](https://leetcode.com/problems/longest-univalue-path/description/).

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

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

## Problem

Given the `root` of a binary tree, return *the length of the longest path, where each node in the path has the same value*. This path may or may not pass through the `root`.

The **length** of the path between two nodes is represented by the number of edges between them.

### Examples

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

```
Input: root = [5,4,5,1,1,null,5]
Output: 2
```

**Explanation:** The shown image shows that the longest path of the same value (i.e. 5).

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

```
Input: root = [1,4,5,4,4,null,5]
Output: 2
```

**Explanation:** The shown image shows that the longest path of the same value (i.e. 4).

### Constraints

* The number of nodes in the tree is in the range \[0, 10^4].
* -1000 \<= Node.val \<= 1000
* The depth of the tree will not exceed 1000.

## Solution

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

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


class Solution:
    # Time: O(n)
    # Space: O(h)
    def longest_univalue_path(self, root: TreeNode[int] | None) -> int:
        # Iterative post-order: depth can reach 1000, so avoid recursion limits.
        best = 0
        stack: list[tuple[TreeNode[int] | None, bool]] = [(root, False)] if root else []
        arrow: dict[int, int] = {}
        while stack:
            node, processed = stack.pop()
            if node is None:
                continue
            if not processed:
                stack.append((node, True))
                stack.append((node.left, False))
                stack.append((node.right, False))
                continue
            left = 0
            left_child = node.left
            if left_child is not None and left_child.val == node.val:
                left = arrow[id(left_child)] + 1
            right = 0
            right_child = node.right
            if right_child is not None and right_child.val == node.val:
                right = arrow[id(right_child)] + 1
            arrow[id(node)] = max(left, right)
            best = max(best, left + right)
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(h) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.