Longest Univalue Path - Problem
Longest Univalue Path challenges you to find the longest sequence of connected nodes in a binary tree where all nodes have the same value.

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

The length of the path is measured by the number of edges between nodes, not the number of nodes themselves. For example, a path with 3 nodes has length 2 (2 edges connecting them).

Key Points:
  • Path can start and end at any nodes
  • All nodes in the path must have identical values
  • Return the count of edges, not nodes
  • Path doesn't need to go through the root

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [5,4,5,1,1,null,5]
โ€บ Output: 2
๐Ÿ’ก Note: The longest univalue path is [5,5,5] which has length 2 (2 edges between 3 nodes). The path goes from one leaf node with value 5, through the root, to another node with value 5.
example_2.py โ€” Single Value Tree
$ Input: root = [1,1,1,1,1,1,1]
โ€บ Output: 4
๐Ÿ’ก Note: All nodes have the same value 1. The longest path goes through the root connecting both subtrees, giving us a path of length 4.
example_3.py โ€” No Matching Values
$ Input: root = [1,2,3,4,5,6,7]
โ€บ Output: 0
๐Ÿ’ก Note: No two adjacent nodes have the same value, so the longest univalue path has length 0.

Visualization

Tap to expand
5515255Longest Univalue Path = 3 edgesPath: 5โ†’5โ†’5โ†’5
Understanding the Visualization
1
Start at Any Tree
Begin DFS traversal from the root tree
2
Explore Both Directions
Check how far you can go left and right with same color
3
Combine Paths
The longest trail through this tree combines left and right distances
4
Track Maximum
Remember the longest trail found so far
5
Return Single Direction
Tell parent tree the longest single-direction path available
Key Takeaway
๐ŸŽฏ Key Insight: At each node, the longest univalue path through it equals the sum of longest same-value paths extending left and right

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

For each of n nodes, we potentially traverse the entire tree again

n
2n
โš  Quadratic Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • Node values are in the range [-1000, 1000]
  • The depth of the tree will not exceed 1000
  • Path length is measured by edges, not nodes
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 22
42.4K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen