InterviewPrepKit

Home / Coding / Trees

Flatten Binary Tree to Linked List

medium Original ↗
Solving tips
  • Target order is preorder, so each node's left subtree must be spliced between the node and its original right subtree.
  • O(1)-space Morris-style trick: for each node with a left child, find the rightmost node of that left subtree, attach the current right subtree there, move the left subtree to the right, null the left, then advance right.
  • Recursive alternative: flatten left and right first, splice, and return the tail of each chain so the parent stitches in O(1) without re-walking (O(h) stack).
  • Pitfall: save curr.right before overwriting it, always null every left pointer, and attach to the left subtree's RIGHTMOST node (its preorder last), not the left child itself.

Problem

You are given the root of a binary tree. Flatten it in place into a “linked list”:

  • Reuse the existing TreeNode objects. For every node, set its left child to None and its right child to the next node in the flattened order.
  • The order must match a pre-order traversal of the original tree (visit the node, then its left subtree, then its right subtree).

After flattening, the whole tree is a right-leaning chain: following right pointers from the root visits every node exactly once in pre-order, and every left pointer is None.

Examples

Example 1

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]

Pre-order is 1,2,3,4,5,6. The result is that sequence linked entirely through right pointers.

Example 2

Input: root = []
Output: []

An empty tree stays empty.

Example 3

Input: root = [0]
Output: [0]

A single node is already a valid flattened list.

Constraints

  • The number of nodes is in the range [0, 2000].
  • -100 <= Node.val <= 100
  • Aim to do it in place; a follow-up asks for O(1) extra space (beyond the recursion/traversal, ideally constant auxiliary memory).

Think about it first

Hint 1 The target order is pre-order: node, then everything in the left subtree, then everything in the right subtree. So each node's left subtree must be spliced in *between* the node and its original right subtree.
Hint 2 For a given node, if you have already flattened its left and right subtrees, how do you stitch them together? Move the flattened left chain into the right pointer, then find the end of that chain and attach the old right chain there.
Hint 3 There is an elegant O(1)-space method: traverse with a current pointer. Whenever the current node has a left child, find that left subtree's rightmost node (its pre-order last), attach the current node's right subtree there, move the whole left subtree to the right, and null the left. Then advance to the right.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.