Longest Univalue Path - 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.

Input & Output

Example 1 — Basic Tree
$ Input: root = [5,4,5,1,1,null,5]
Output: 2
💡 Note: The longest path with same values is 5→5→5 from root through right child to its right child, giving length 2 (2 edges)
Example 2 — Single Value Tree
$ Input: root = [1,4,5,4,4,null,5]
Output: 2
💡 Note: The longest same-value path is 4→4→4 in the left subtree, with length 2
Example 3 — All Same Values
$ Input: root = [1,1,1,1,1,1,1]
Output: 4
💡 Note: Multiple paths exist, longest goes through root connecting both subtrees: 1→1→1→1→1 with length 4

Constraints

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 ≤ Node.val ≤ 1000
  • The depth of the tree will not exceed 1000.

Visualization

Tap to expand
Longest Univalue Path Problem545115Input: [5,4,5,1,1,null,5]Longest same-value path: 5→5→5Path length = 2 edgesOutput: 2Red nodes and thick lines show the longest univalue path
Understanding the Visualization
1
Input Tree
Binary tree with various node values
2
Find Same-Value Paths
Identify all paths where nodes have identical values
3
Return Length
Count edges in the longest same-value path
Key Takeaway
🎯 Key Insight: Use DFS to combine left and right same-value path lengths at each node to find the global maximum
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
52.0K Views
Medium Frequency
~25 min Avg. Time
2.2K 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