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 INPUT Binary Tree Structure 5 4 5 1 1 5 Array representation: [5, 4, 5, 1, 1, null, 5] Green = Longest Univalue Path ALGORITHM STEPS Optimized DFS Approach 1 DFS Traversal Recursively visit each node in post-order manner 2 Compare Values Check if child value equals parent value 3 Extend Path If equal, add 1 to path length from child 4 Update Maximum Track max path through each node (left+right) Path Calculation at Node 5 5 5 left=0, right=1 path = 0+1 = 1 FINAL RESULT Longest Univalue Path Found 5 4 5 5 1 1 Path: 5 --> 5 --> 5 (2 edges connecting 3 nodes) Output: 2 Key Insight: The DFS returns the longest single-direction path (left OR right) to parent, but tracks the global max as the sum of both directions (left + right) through each node. Path length = number of EDGES, not nodes. A path through root 5 has left=0, right=2, max=2. TutorialsPoint - Longest Univalue Path | Optimized DFS Approach
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