Longest Alternating Left-Right Path in a Decision Tree
Last updated: November 29, 2026
Quick Overview
In a binary decision tree, a zigzag path starts at any node and moves to a child, alternating between left and right steps each time. Return the number of edges in the longest zigzag path.
0
0
0 solved
In a binary decision tree, a zigzag path starts at any node and moves to a child, alternating between left and right steps each time. Return the number of edges in the longest zigzag path.
Posed in Google technical screens for ML-adjacent roles using a decision tree framing, where alternating splits indicate unstable features. The interviewer checks that you carry the direction of the last step and reset correctly when the pattern breaks.
What the Interviewer Expects
- Track two values per node: longest zigzag arriving via a left step and via a right step
- Extend the chain when the direction alternates
- Restart at length 1 when it repeats
- Do it in a single DFS
- State O(n) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the start node of the longest path.
- Count zigzag paths of length at least k.
- What if the path may also go upward?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: root. Output: maximum number of edges in a downward path whose steps alternate left and right. A single node has length 0. Empty tree returns 0....
High-Level Design
Push (node, came_left, length) on a stack, where length is the zigzag length of the best path ending at this node whose last step had the given direction. For a node reached by a left step with le...