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 / 13
5
curr
4
5
1
1
5
5
04
15
21
31
45
5Visiting 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.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run: [5, 4, 5, 1, 1, 5]
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
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.
