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.
10 min read
Solve on LeetCodeExamples
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:
- Recursive calls get the longest univalue path extending down from left and right children.
- Check Value:
- If
node.leftexists andnode.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.
- If
- Update Global Max:
maxPath = max(maxPath, arrowLeft + arrowRight). - 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.
ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
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.
