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
rightpointer points to the next node of the list, and everyleftpointer isnull; - 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.
- The number of nodes in the tree is in the range [0, 2000].
- -100 <= Node.val <= 100
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.
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.
Approach
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.
Two ways to solve it
Fix one node at a time: hang its right subtree under the left subtree's rightmost node, then move the left subtree across.
- No recursion: meets the O(1) follow-up.
- Safe on deep trees: a 2,000-node chain is no problem.
The answer the follow-up wants.
Visit nodes right subtree first, then left, then the node, and link each node to the one visited before it.
- Short: five lines of logic.
- Uses the call stack: O(h) memory, and Python needs a higher recursion limit.
The common first answer.
Both finish in O(n). The iterative version also needs no call stack, so the steps, code and demo follow it; the recursive version comes after the demo.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
right. Start the cursor at the root. Every node the cursor has passed will already have no left child.tail right to 4.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.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.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.right. Start the cursor at the root. Every node the cursor has passed will already have no left child.left.left.right now leads to the next node in preorder (1 → 2 → 3) and every left is None. No extra list or stack was used.cur starts as None, so the while loop never runs. An empty tree is already a valid empty list, and the function simply returns.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.
Common pitfalls
Moving the left subtree before saving the right one
cur.right = cur.left cur.left = None
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
cur.left.right = cur.right
tail = cur.left
while tail.right:
tail = tail.right
tail.right = cur.rightThe 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
cur.right = cur.left
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
return linked_list_of(preorder(root))
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.
Edge cases
[]cur starts as null, the loop never runs, and nothing needs to change.
[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.
Complexity
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).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.