← Questions

Flatten a binary tree to a linked list

0
MetaCodingLast asked Aug 2025

A coding interview question asked in Meta's recruiter screen, last asked Aug 2025. It tests binary tree and dfs.

Flatten a binary tree in place into a chain that follows pre-order: each node's right pointer points to the next node in pre-order, and every left pointer is None.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • flatten(root: TreeNode | None) -> None — rewires the existing nodes. Creates no new nodes.

Example

        1
       / \
      2   5
     / \   \
    3   4   6

flatten(root)   ->  1 -> 2 -> 3 -> 4 -> 5 -> 6     # all through right pointers, every left is None

Constraints

  • Up to 2000 nodes, or many more if you discuss deep trees.
  • Aim for O(1) extra space in the final version.

Clarifying questions

  • Must it be in place, or may I build a new list?
  • Pre-order specifically, or would in-order do?
  • How deep can the tree be? That decides between recursion and iteration.

What a strong answer covers

  • A recursive version: flatten both subtrees, put the flattened left subtree between the node and its flattened right subtree. O(n) time, O(h) stack.
  • Reverse pre-order (right, left, node) with a prev pointer, which links nodes in one walk.
  • An O(1)-space version in the style of Morris traversal: for each node with a left child, find the rightmost node of the left subtree, attach the right subtree there, move the left subtree to the right, and continue.
  • A correctness argument: after each step the chain so far is in pre-order and nothing is lost.
  • Tests: an empty tree, one node, a left-only chain, a right-only chain.

Follow-ups

  • Flatten into in-order instead, as a doubly linked list.
  • Undo the flattening: rebuild the tree from the chain, if extra information is kept.
  • Flatten a multilevel doubly linked list with child pointers.

Where it's asked

What it tests

binary tree · dfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding