15% off all plans & roadmaps Use code

See plans

Flatten Binary Tree to Linked List

Updated

TL;DR: Rewire the tree so every left pointer is null and the right pointers follow preorder order. Splice each left subtree between its node and the old right subtree. This runs in O(n) time and O(1) extra space.

Problem

Given the root of a binary tree, flatten the tree into a "linked list".

  • The linked list uses the same TreeNode class. The right pointer of each node points to the next node in the list, and the left pointer is always null.
  • The list must follow the same order as a preorder traversal of the original tree.

Example 1

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

Example 2

Input: root = []
Output: []

Example 3

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

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Constraints that matter

  • n up to 2000 means an O(n^2) approach that rescans the tree for every node is too slow in the worst case, so each node should be touched a constant number of times.
  • n up to 2000 also means a skewed tree can be 2000 levels deep, which is enough to overflow a recursive call stack in Python with its default limit of 1000 frames.
  • Values range from -100 to 100, so values never matter. Only the shape of the tree affects the answer.
  • The output must reuse the existing nodes, so the solution must rewire pointers rather than build new nodes.

View on LeetCode

Hints

Hint 1

Preorder visits the root first, then the whole left subtree, then the whole right subtree.

Hint 2

Collect the nodes in preorder into an array, then rewrite each node so that its right points at the next array entry and its left is null.

Solution

Intuition

Preorder visits the root first, then the whole left subtree, then the whole right subtree. The flattened list must therefore place the root, then the flattened left subtree, then the flattened right subtree. This is a tree DFS problem, and the order is the preorder order.

The key question is where the old right subtree goes. If a node has a left child, the left subtree must sit between the node and its right subtree. The last node of the left subtree in preorder is its rightmost node, so the old right subtree should hang from that node. Once you see this, the problem becomes pointer splicing.

You can walk the main chain from the root with one pointer and splice as you go. Each splice moves a left subtree to the right side, and the walk then continues down the new right side. A breadth-first search does not fit, because level order visits siblings before children and does not match preorder.

Watch the pattern animation

Worked example

Input: root = [7,null,8,null,9,null,10]
Output: [7,null,8,null,9,null,10]
Explanation: The tree leans right and has no left children, so its preorder is already 7, 8, 9, 10. Every left pointer is null, so the output matches the input. The splice step never fires on this tree, so the dry runs below also trace a small tree where it does.

Approach 1: Brute force: preorder list, then relink

Collect the nodes in preorder into an array, then rewrite each node so that its right points at the next array entry and its left is null. The array holds every node, and the pass over the array then rewrites the pointers. The result is correct, but it uses O(n) extra space, which the follow-up forbids. The first pass also visits every node before the second pass changes anything, so the logic is easy to check.

Steps

  1. Create an empty list and an explicit stack, and push the root if it exists.
  2. Pop a node, append it to the list, then push its right child and then its left child so the left child comes off the stack first.
  3. Repeat until the stack is empty. The list now holds the nodes in preorder.
  4. For each index i from 0 to n - 2, set nodes[i].left to null and nodes[i].right to nodes[i + 1].
  5. Set the last node's left and right to null.

Dry run

Use the example tree 7 with right child 8, then 9, then 10. Start with the stack holding [7]. Pop 7 and append it, so the list is [7]. Push 8.

Pop 8, append it, so the list is [7, 8]. Push 9. Pop 9, list [7, 8, 9], push 10. Pop 10, list [7, 8, 9, 10], and the stack is empty.

Relink the pairs. Set 7.right to 8, 8.right to 9, 9.right to 10, and 10.right to null. Every left pointer is already null. The final structure is 7, 8, 9, 10, which gives the output [7,null,8,null,9,null,10].

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of nodes. The stack loop pushes and pops each node exactly once, so it does n pushes and n pops, each in constant time. The relink loop makes n - 1 constant-time pointer writes, so the total is O(n). The list stores all n node references, and the stack never holds more than n entries, so the extra space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        # Collect nodes in preorder using an explicit stack.
        nodes = []
        stack = [root] if root else []
        while stack:
            node = stack.pop()
            nodes.append(node)
            # Push right first so the left child is popped first.
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        # Relink each node to the next one in the list.
        for i in range(len(nodes) - 1):
            nodes[i].left = None
            nodes[i].right = nodes[i + 1]
        if nodes:
            nodes[-1].left = None
            nodes[-1].right = None

The Recursive Preorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Preorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: O(1) space pointer spliceOptimalRecursive Preorder Traversal

What is slow in the list version is the array. It holds every node only so the second pass can find the next node.

The insight that fixes it: the next node in preorder is known from the tree itself. For a node with a left child, that next node is the left child. The end of the left subtree, its rightmost node, then links to the old right subtree.

So a single pointer walking the main chain does all the rewiring, with no array and no recursion.

Steps

  1. Set cur to the root.
  2. If cur has no left child, move cur to cur.right and skip to the next step of the loop.
  3. Otherwise, set pred to cur.left and walk right until pred.right is null. This finds the rightmost node of the left subtree.
  4. Set pred.right to cur.right, which reattaches the old right subtree after the left subtree.
  5. Set cur.right to cur.left, set cur.left to null, and move cur to cur.right.
  6. Stop when cur is null.

Dry run

Trace the example first. Every node has no left child, so each step only moves right.

Stepcurcur.leftActioncur.right after the step
17nullno left child, move right8
28nullno left child, move right9
39nullno left child, move right10
410nullno left child, move rightnull
5nulln/aloop endsn/a

The chain 7, 8, 9, 10 is unchanged, and every left pointer is null. The output is [7,null,8,null,9,null,10].

Now trace a tree where the splice fires. Take root 1 with left child 2, right child 4, and 2.right = 3. Preorder is 1, 2, 3, 4.

Stepcurcur.leftActionResult so far
112pred walks 2, 3; stops at 33.right = 4
212cur.right = 2, cur.left = null1 -> 2 -> 3 -> 4
32nullmove rightat 3
43nullmove rightat 4
54nullmove right, loop endsdone

The final chain is 1, 2, 3, 4, which matches preorder.

Complexity

TimeO(n)
SpaceO(1)

Let n be the number of nodes. The outer loop advances cur one node at a time along the main chain, so it runs at most n times. Each pred walk moves down the right spine of a left subtree. Once that spine is spliced, its nodes sit on the main chain ahead of cur, so cur never walks them again as a pred walk.

That bounds the total pred steps by n, so the time is O(n). The loop uses a fixed number of pointers and no recursion or array, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        cur = root
        while cur:
            if cur.left:
                # The rightmost node of the left subtree comes just before cur.right in preorder.
                pred = cur.left
                while pred.right:
                    pred = pred.right
                pred.right = cur.right
                # Move the left subtree to the right side.
                cur.right = cur.left
                cur.left = None
            cur = cur.right

Common mistakes

  • cur.right = cur.left before pred.right = cur.right: the old right subtree is lost. Save it or attach it to pred first, as the optimal code does.
  • Leaving cur.left set after the splice. Every left pointer must be null, and a leftover left child makes the walk revisit nodes.
  • pred = pred.left in the inner loop: the walk must follow right pointers, or it stops at the wrong node and attaches the old right subtree in the wrong place.
  • Writing cur = cur.left after the splice. The left pointer is now null, so the walk stops early. Always advance with cur = cur.right.
  • Recursive preorder with a single prev pointer that visits left before right. It overwrites right before the right child is read. Process the right subtree first, or use the splice.
  • Using recursion on a skewed tree of 2000 nodes in Python. The default recursion limit is 1000, so the call stack overflows. The iterative splice avoids this.

Edge cases

  • root is null: the function returns without changes, and the expected output is an empty tree.
  • single node [0]: the node stays as it is, with a null left pointer and a null right pointer.
  • a tree that is a left-only chain, such as 1 with left 2 and 2 with left 3: the result is the right chain 1, 2, 3.
  • a tree that is already a right chain, like the example: nothing changes.
  • a complete tree with 2000 nodes and repeated values: the algorithm depends only on shape, so duplicates have no effect.
  • negative values such as -100: values are copied through untouched and never compared.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Flatten Binary Tree to Linked List, with how to answer them.

Unlock the follow-ups

Flatten Binary Tree to Linked List FAQ

What is the time complexity of Flatten Binary Tree to Linked List?

Both approaches run in O(n) time, where n is the number of nodes. The list version does two passes over the nodes, and the splice does one walk with pred walks that total at most n steps.

Why use pointer splicing for Flatten Binary Tree to Linked List?

Preorder places the left subtree between a node and its right subtree. Splicing moves the left subtree into that slot and reattaches the old right subtree after it, which reuses the existing nodes. The splice avoids the array that the list version needs.

Can Flatten Binary Tree to Linked List be solved in O(1) extra space?

Yes, with the iterative splice. A recursive solution needs O(h) stack space, where h is the height, which is O(n) on a skewed tree. The O(1) bound refers to extra space beyond the tree itself.

Why is BFS not the right traversal for LeetCode 114?

Breadth-first search visits all nodes at one depth before going deeper, so it does not produce preorder. The flattened list must follow root, left subtree, right subtree, which is a depth-first order.

Why does a recursive solution for flatten binary tree to linked list fail in Python on a deep tree?

Python's default recursion limit is 1000 frames. A skewed tree with 2000 nodes needs 2000 frames, so the call raises RecursionError. Use the iterative splice to avoid recursion entirely.

Asked at

See which companies ask this — Pro

Practise it