Depth-First Search
Medium

Longest Univalue Path

Find the length of the longest path where each node in the path has the same value.
Examples
Input:root = [5,4,5,1,1,5]
Output:2
Explain:

The longest path of value 5 is 5 -> 5 -> 5 (length 2).

Problem Understanding

We need the longest path (edges) where every node has the same value.

Like Diameter, the path does not need to pass through the root. It can form an inverted 'V' shape at any mode.

Algorithm Strategy

We use Post-Order DFS.

At each node:

  1. Recursive calls get the longest univalue path extending down from left and right children.
  2. Check Value:
    • If node.left exists and node.left.val == node.val, we can extend the left path by 1.
    • Otherwise, the path from the left stops here (RESET to 0).
    • Same logic for right child.
  3. Update Global Max: maxPath = max(maxPath, arrowLeft + arrowRight).
  4. Return: max(arrowLeft, arrowRight) (we can only extend one branch up to the parent).
Interactive Visualization
Step 1 / 13
5
curr
4
5
1
1
5
5
0
4
1
5
2
1
3
1
4
5
5

Visiting Node 5. Asking children for univalue path extensions...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep