LeetCode #114 Medium

Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List is LeetCode 114 (Medium). Given the root of a binary tree, rearrange it in place into a "linked list" made of the same nodes:

  • each node's right pointer points to the next node of the list, and every left pointer is null;
  • the list visits the nodes in preorder: the node, then its left subtree, then its right subtree.

The function returns nothing; the tree itself is changed. The follow-up asks for O(1) extra space, so no list of nodes and no stack.

Constraints
  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100
treemorrisin-place
Open on LeetCode ↗
02

Intuition

Look at one node with a left subtree. In preorder, the whole left subtree comes right after the node, and the right subtree comes after the last node of the left subtree. That last node is the left subtree's rightmost node: keep going right from node.left until you can't.

So one node can be fixed on its own: hang the right subtree under that rightmost node, then move the left subtree into the right slot. The order of every node is unchanged, but this node now has no left child.

Step to node.right and repeat. Each fix only moves pointers further down, so walking right until the end flattens the whole tree.

How to spot this pattern

When a tree must be rewired in place without a stack, look for a spare pointer inside the tree that can remember "what comes next". Here the rightmost node of the left subtree has an empty right pointer, which is exactly where the rest of the preorder belongs.

03

Approach

Try it first

Before reading on: draw a root whose left child has its own right child. In preorder, which node comes just before the root's right child? Then decide which two pointers to change so the root has no left child. Aim for O(n) time and O(1) space.

1

Walk a cursor down the right pointers

Start with cur = root and loop while cur is not null. Every node that is already fixed has no left child, so the remaining work always lies at cur or below it on the right.

2

Skip a node with no left child

If cur.left is null, the next preorder node is already cur.right, so nothing moves. Go straight to the last step and advance.

3

Find the rightmost node of the left subtree

Set tail = cur.left and move tail = tail.right until tail.right is null. Its empty right pointer is the free slot where cur's right subtree will be attached.

4

Hang the right subtree, then move the left one

Set tail.right = cur.right, then cur.right = cur.left and cur.left = None. The right subtree now hangs below the left subtree, and cur points right at what used to be its left child.

5

Advance to the right

Set cur = cur.right. That is the next node in preorder, and its own left subtree, if any, is fixed on the next pass.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def flatten(self, root):
▶3 cur = root
▶4 while cur:
▶5 if cur.left:
▶6 tail = cur.left
▶7 while tail.right:
▶8 tail = tail.right
▶9 tail.right = cur.right
▶10 cur.right = cur.left
▶11 cur.left = None
▶12 cur = cur.right
3241cur56preorder123456start at the root 1
cur1
The goal is the bottom row: the nodes in preorder, linked through right. Start the cursor at the root. Every node the cursor has passed will already have no left child.
32tail41cur56preorder123456tail starts at 2, the left child
cur1
tail2cur.left
Node 1 has a left subtree, so it needs fixing. Its right subtree must follow the last node of that left subtree in preorder, which is the left subtree's rightmost node. Start the search at 2.
324tail1cur56preorder1234562 has a right child → tail moves to 4
tail4moved right from 2
Node 2 still has a right child, so it is not the last node of the left subtree. Move tail right to 4.
324tail561curpreorder123456hang 5 under tail 4
tail.right5was None
Node 4 has no right child, so it is the last node of 1's left subtree. Hang 1's right subtree (5) there: in preorder it comes straight after 4. This saves the subtree before 1's right pointer is overwritten.
1cur32456preorder123456left subtree of 1 moves to its right
cur.right2
cur.leftNone
Now point 1's right at its old left child 2 and clear left. The preorder is unchanged, but 1 is now finished: it has no left child and its right pointer leads to the next node.
132cur456preorder123456move to 2
cur2cur.right of 1
Move the cursor to 2, the next node in preorder. It still has a left subtree, so it needs the same fix.
13tail2cur456preorder123456tail starts at 3, the left child
cur2
tail3cur.left
Node 2 has a left subtree, so it needs fixing. Its right subtree must follow the last node of that left subtree in preorder, which is the left subtree's rightmost node. Start the search at 3.
13tail4562curpreorder123456hang 4 under tail 3
tail.right4was None
Node 3 has no right child, so it is the last node of 2's left subtree. Hang 2's right subtree (4) there: in preorder it comes straight after 3. This saves the subtree before 2's right pointer is overwritten.
12cur3456preorder123456left subtree of 2 moves to its right
cur.right3
cur.leftNone
Now point 2's right at its old left child 3 and clear left. The preorder is unchanged, but 2 is now finished: it has no left child and its right pointer leads to the next node.
123cur456preorder123456move to 3
cur3cur.right of 2
Move the cursor to 3, the next node in preorder.
1234cur56preorder1234563 has no left child → move to 4
cur4cur.right of 3
Node 3 has no left child, so its right child is already the next node in preorder and nothing moves. Step to 4.
12345cur6preorder1234564 has no left child → move to 5
cur5cur.right of 4
Node 4 has no left child, so its right child is already the next node in preorder and nothing moves. Step to 5.
123456curpreorder1234565 has no left child → move to 6
cur6cur.right of 5
Node 5 has no left child, so its right child is already the next node in preorder and nothing moves. Step to 6.
123456preorder123456no node left → flattened
curNone
list1 → 2 → 3 → 4 → 5 → 6
The cursor ran off the end, so every node is fixed. Each node's right now leads to the next node in preorder (1 → 2 → 3 → 4 → 5 → 6) and every left is None. No extra list or stack was used.
05

Reverse preorder recursion

Build the list from its end. Visiting right subtree, then left subtree, then the node is preorder backwards, so the node visited just before node is the one that must follow it. Keep it in prev, point node.right at it, clear node.left, and make node the new prev.

▶1import sys
▶2 
▶3class Solution:
▶4 def flatten(self, root):
▶5 sys.setrecursionlimit(10000)
▶6 self.prev = None
▶7 
▶8 def build(node):
▶9 if not node:
▶10 return
▶11 build(node.right)
▶12 build(node.left)
▶13 node.right = self.prev
▶14 node.left = None
▶15 self.prev = node
▶16 
▶17 build(root)
06

Common pitfalls

Moving the left subtree before saving the right one

✗ Wrong
cur.right = cur.left
cur.left = None
✓ Right
tail.right = cur.right
cur.right = cur.left
cur.left = None

Once cur.right is overwritten, nothing points to the old right subtree any more. On [1,2,5,3,4,null,6] the result is 1 → 2 → 3: nodes 5 and 6 are lost at the root, and node 4 is lost at node 2.

Hanging the right subtree on the left child itself

✗ Wrong
cur.left.right = cur.right
✓ Right
tail = cur.left
while tail.right:
    tail = tail.right
tail.right = cur.right

The left child may already have a right child. On [1,2,5,3,4,null,6] this overwrites 2's link to 4, so node 4 disappears from the list.

Forgetting to clear the left pointer

✗ Wrong
cur.right = cur.left
✓ Right
cur.right = cur.left
cur.left = None

Node 2 is then reachable both as the left and the right child of node 1. The right chain looks correct, but the judge also checks every left pointer and rejects the tree.

Building a new list instead of rewiring

✗ Wrong
return linked_list_of(preorder(root))
✓ Right
rewire root's own pointers and return nothing

The function's return value is ignored. Only the original nodes are checked, so a fresh list, even a correct one, fails on every tree that was not already flat.

07

Edge cases

An empty tree, []

cur starts as null, the loop never runs, and nothing needs to change.

Every node has only a left child, such as [1,2,null,3]

Each tail is simply cur.left, because it has no right child. The empty right subtree is hung there, the left child moves right, and the chain 1 → 2 → 3 comes out.

08

Complexity

Time
O(n)
Space
O(1)
The cursor visits each node once. The tail walks only follow right pointers inside left subtrees, and each such pointer is walked at most once before it becomes part of the finished chain, so all walks together cost O(n).
09

Flatten Binary Tree to Linked List FAQ

Is this the same as a Morris traversal?

It uses the same trick: the rightmost node of the left subtree holds a link to what comes next, so no stack is needed. Morris traversal removes that link later to restore the tree; here the link is kept, because it is part of the answer.