15% off all plans & roadmaps Use code
See plansFlatten Binary Tree to Linked List
- LeetCode 114
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Recursive Preorder Traversal
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
TreeNodeclass. Therightpointer of each node points to the next node in the list, and theleftpointer is alwaysnull. - 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.
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.
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
- Create an empty list and an explicit stack, and push the root if it exists.
- 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.
- Repeat until the stack is empty. The list now holds the nodes in preorder.
- For each index i from 0 to n - 2, set
nodes[i].leftto null andnodes[i].righttonodes[i + 1]. - Set the last node's
leftandrightto 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
| Time | O(n) |
|---|---|
| Space | O(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 = NoneThe 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 infographicSolution pattern
Recursive Preorder Traversal
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
- Set
curto the root. - If
curhas no left child, movecurtocur.rightand skip to the next step of the loop. - Otherwise, set
predtocur.leftand walk right untilpred.rightis null. This finds the rightmost node of the left subtree. - Set
pred.righttocur.right, which reattaches the old right subtree after the left subtree. - Set
cur.righttocur.left, setcur.leftto null, and movecurtocur.right. - Stop when
curis null.
Dry run
Trace the example first. Every node has no left child, so each step only moves right.
| Step | cur | cur.left | Action | cur.right after the step |
|---|---|---|---|---|
| 1 | 7 | null | no left child, move right | 8 |
| 2 | 8 | null | no left child, move right | 9 |
| 3 | 9 | null | no left child, move right | 10 |
| 4 | 10 | null | no left child, move right | null |
| 5 | null | n/a | loop ends | n/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.
| Step | cur | cur.left | Action | Result so far |
|---|---|---|---|---|
| 1 | 1 | 2 | pred walks 2, 3; stops at 3 | 3.right = 4 |
| 2 | 1 | 2 | cur.right = 2, cur.left = null | 1 -> 2 -> 3 -> 4 |
| 3 | 2 | null | move right | at 3 |
| 4 | 3 | null | move right | at 4 |
| 5 | 4 | null | move right, loop ends | done |
The final chain is 1, 2, 3, 4, which matches preorder.
Complexity
| Time | O(n) |
|---|---|
| Space | O(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.rightCommon mistakes
cur.right = cur.leftbeforepred.right = cur.right: the old right subtree is lost. Save it or attach it topredfirst, as the optimal code does.- Leaving
cur.leftset after the splice. Every left pointer must be null, and a leftover left child makes the walk revisit nodes. pred = pred.leftin the inner loop: the walk must followrightpointers, or it stops at the wrong node and attaches the old right subtree in the wrong place.- Writing
cur = cur.leftafter the splice. The left pointer is now null, so the walk stops early. Always advance withcur = cur.right. - Recursive preorder with a single
prevpointer that visits left before right. It overwritesrightbefore 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-upsFlatten 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
Related problems
- Construct Binary Tree from Preorder and Inorder Traversal · same technique: Recursive Preorder Traversal
- Count Good Nodes in Binary Tree · same technique: Recursive Preorder Traversal
- Insert into a Binary Search Tree · same technique: Recursive Preorder Traversal
- Construct Quad Tree · same technique: Recursive Preorder Traversal
- Smallest String Starting From Leaf · same technique: Recursive Preorder Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Level Order Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Right Side View · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)