Browse Curriculum
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 / 1
Empty Heap

Initializing...

1x

Visualize how we reset counts when values mismatch.

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.