Skip to main content
LeetCode 687, Medium. Topics: Tree, Depth-First Search, Binary Tree, Dynamic Programming. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

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
Explanation: The shown image shows that the longest path of the same value (i.e. 5). Example 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, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026