PPractick

DSA interview question

Flatten a Binary Tree to a Linked List

Medium · Data structures · Topics: tree, dfs, linkedlist

The problem

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.

Function signature

void flatten(TreeNode* root);  // in place: right = next in preorder, left = nullptr

Test cases

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.)

How interviewers phrase it

Clarifying questions to ask

  1. Preorder order? (Yes.)
  2. Must it be in place? (Yes, and O(1) extra space is the follow-up.)
  3. Should left pointers be set to null? (Yes.)

Follow-ups to expect

  1. "Why the rightmost node of the left subtree?"
  2. "Recursive alternative?"
  3. "Stack alternative?"
  4. "Why is the rewiring approach O(n)?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in