DSA interview question
A UI framework stores a menu as a binary tree but needs to render it as a flat list in preorder, reusing the same nodes: each node's right pointer becomes "next" and every left pointer becomes null. It must be done in place. The O(1)-space approach is Morris-like. For each node with a left subtree, attach the node's current right subtree to the rightmost node of the left subtree (the last node the left part visits in preorder), move the left subtree to the right, and continue down the right pointers.
Example: [1, 2, 5, 3, 4, null, 6] → 1 → 2 → 3 → 4 → 5 → 6.
void flatten(TreeNode* root); // in place: right = next in preorder, left = nullptr
| Input (level order) | Output (level order after flattening) | Explanation |
|---|---|---|
[1, 2, 5, 3, 4, null, 6] | [1, null, 2, null, 3, null, 4, null, 5, null, 6] | |
[1, 2] | [1, null, 2] | |
[1, null, 2, 3] | [1, null, 2, null, 3] | |
[0] | [0] | |
[] | [] |
(Confirm: the resulting list follows preorder; all left pointers must be null; no new nodes.)
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