DSA interview question
A visualisation of a family tree animates the generations in a snake pattern: the first row left to right, the next row right to left, then left to right again, like a spiral. It's level-order BFS, except every other level is reversed. Keep a direction flag that flips after each level, and fill each level's list from the front or from the back depending on the flag.
Example: [3, 9, 20, null, null, 15, 7] → [[3], [20, 9], [15, 7]].
vector<vector<int>> zigzagLevelOrder(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[3, 9, 20, null, null, 15, 7] | [[3], [20, 9], [15, 7]] | |
[1, 2, 3, 4, 5, 6, 7] | [[1], [3, 2], [4, 5, 6, 7]] | |
[1, 2, 3, 4, null, null, 5] | [[1], [3, 2], [4, 5]] | |
[1] | [[1]] | |
[] | [] |
(Confirm: level 0 is left to right, level 1 right to left, and so on.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in