Flatten Binary Tree to Linked List explained
To flatten a binary tree into a linked list in place, rewire it so each node's right pointer leads to the next node in preorder and every left pointer is empty. The neatest constant-space method walks down the right side: whenever a node has a left subtree, hang the node's old right subtree off the rightmost node of that left subtree, then move the left subtree over to the right. That is O(n) time and O(1) extra space.
By Evin JohnPublished 8 min read
The task, reworded
You get the root of a binary tree. Change the tree itself, without creating new nodes, so that it becomes a single chain going right: the root first, then the nodes in preorder. Each node's left pointer must end up empty. Nothing is returned; the caller still holds the root, which is now the head of the chain.
7
/ \
3 9 7 -> 3 -> 2 -> 5 -> 9 -> 8 -> 11
/ / \
2 8 11 (every arrow is a right pointer,
\ every left pointer is empty)
5Confirm two things up front: the order is preorder, and the work must happen in place. Some interviewers then add a constraint of O(1) extra space, which rules out both a list of nodes and plain recursion on a deep tree.
What this problem checks
Pointer rewiring is where tree code goes wrong in interviews: one assignment in the wrong order and a whole subtree disappears. This problem tests whether you can plan the order of assignments, explain why nothing is lost, and then improve the memory use step by step. It also rewards spotting that preorder can be built from the back.
Baseline: record preorder, then relink
Walk the tree in preorder and store the nodes in a list. Then go through the list and set each node's left to empty and its right to the next node. It is simple and hard to get wrong, which makes it a good first answer and a reference for testing. It uses O(n) extra memory for the list.
Recursion that builds the chain from the end
If you visit nodes in exactly the reverse of preorder, which is right subtree, then left subtree, then the node, each node is reached just after the node that should follow it in the chain. Keep a variable prev holding the most recently finished node. When you finish a node, point its right at prev, clear its left, and make it the new prev. The children have already been read before the pointers change, so nothing is lost.
def flatten_recursive(root):
prev = None
def build(node):
# visit right, then left, then the node: preorder in reverse
nonlocal prev
if node is None:
return
build(node.right)
build(node.left)
node.right = prev
node.left = None
prev = node
build(root)Constant space: splice left subtrees into place
Walk down the right pointers from the root. At each node with a left subtree, three assignments do the work. First, find the rightmost node of the left subtree, call it tail; its empty right pointer is the last spot preorder visits inside that subtree. Second, attach the node's current right subtree to tail.right, so the right side now comes after the entire left side. Third, move the left subtree to node.right and clear node.left. Then step to node.right and repeat.
def flatten_in_place(root):
node = root
while node is not None:
if node.left is not None:
# rightmost node of the left subtree: its empty right pointer
# is the last spot preorder reaches inside that subtree
tail = node.left
while tail.right is not None:
tail = tail.right
tail.right = node.right # hang the old right subtree there
node.right = node.left # move the left subtree to the right
node.left = None
node = node.rightstruct TreeNode {
int val;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
explicit TreeNode(int v) : val(v) {}
};
void flattenInPlace(TreeNode* root) {
for (TreeNode* node = root; node != nullptr; node = node->right) {
if (node->left == nullptr) continue;
TreeNode* tail = node->left;
while (tail->right != nullptr) tail = tail->right;
tail->right = node->right;
node->right = node->left;
node->left = nullptr;
}
}Trace on the example
At 7, the left subtree is 3 and its rightmost node is 3 itself, since 3 has no right child. The 9 subtree is hung on 3.right, then 3 moves to 7.right. The tree is now 7 → 3, with 3 holding 2 on its left and 9 on its right. At 3, the left subtree is 2, whose rightmost node is 5. The 9 subtree moves to 5.right and 2 moves to 3.right. At 2 there is no left child, so the walk continues to 5, then 9. At 9, the left subtree is 8, the 11 is hung on 8.right, and 8 moves over. The chain reads 7, 3, 2, 5, 9, 8, 11.
Why is it still linear when each node searches for a tail? Each tail search walks down right pointers inside one left subtree. After the splice, those nodes sit on the main chain and the walk only ever steps over them once more, so each node is touched a constant number of times overall.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Preorder into a list, then relink | O(n) | O(n) |
| Explicit stack, linking as you pop | O(n) | O(h) |
| Reverse preorder recursion with prev | O(n) | O(h) call stack |
| Splice loop | O(n) | O(1) |
Edge cases
- Empty tree: nothing to do; the loop never starts.
- A tree that is already a right-leaning chain: no node has a left child, so nothing changes.
- A left-leaning chain: every node splices once and the tail search is a single step each time.
- Nodes with only a left child: the old right subtree is empty, so tail.right simply stays empty.
Mistakes that lose subtrees
- Setting node.right = node.left before saving the old right subtree. The right side is gone.
- Forgetting node.left = None, which leaves a structure that is both a chain and a tree, and fails the check.
- In the recursive version, visiting left before right, which builds the chain in the wrong order.
- Creating new nodes or returning a new list when the task asks for an in-place change.
- Using a global prev that is never reset between calls in a test harness, so a second test case links into the first.
Follow-up questions
- Flatten in in-order instead. The chain would then be sorted for a search tree. The reverse-order trick still works if you visit right, node, left, as long as you save the left child before overwriting the node's pointers.
- Make it a doubly linked list. Use left pointers as back links: set each node's left to the previous node as you link.
- Circular list. After flattening, connect the tail back to the head.
- Undo it. A flattened chain has lost the tree's shape; you would need extra information, such as subtree sizes, to rebuild it.
Talking through it
Fictional example
- Candidate
- The easy version stores preorder in a list and relinks, but that's linear extra memory. I can do it in place.
- Candidate
- Walking down the right side, when a node has a left subtree, I find that subtree's rightmost node. Preorder finishes the left side there, so I attach the node's old right subtree to it, then move the left subtree over to the right and clear the left pointer.
- Candidate
- Every node is stepped over a constant number of times, so it's linear time with constant extra space. If recursion is fine, building the chain in reverse preorder with a prev pointer is even shorter.
Related walkthroughs
Binary Tree Inorder Traversal covers Morris threading, which uses the same rightmost-of-the-left-subtree step but restores the tree afterward. Path Sum II walks the tree in preorder too, recording paths instead of rewiring. Binary Tree Zigzag Level Order Traversal is a breadth-first walk, for contrast. The coding problems hub has more.
Practicing pointer problems with Natively
Practicing on a Mac or a Windows PC, you can have Natively read this problem from a screenshot and ask it to walk the splice on a small tree so you can compare against your own trace. It transcribes the mock and saves notes, which helps you check whether you said why the old right subtree is safe before you moved it. The AI interview assistant page explains more.
Questions people ask
How do you flatten a binary tree to a linked list in place?
Walk down the right pointers. At each node with a left subtree, find that subtree's rightmost node, attach the node's right subtree there, move the left subtree to the right and clear the left pointer. Then continue to the right.
Can you flatten a binary tree in O(1) space?
Yes. The splice loop uses no stack or list, because the rightmost node of each left subtree is exactly where the right subtree belongs in preorder.
What order does Flatten Binary Tree to Linked List use?
Preorder: the node, then its left subtree, then its right subtree. The chain follows right pointers and every left pointer is empty.
What is the recursive solution to Flatten Binary Tree?
Visit right, then left, then the node, keeping the previously finished node. Point each node's right at that previous node and clear its left. This builds the preorder chain from the end in O(n) time.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
