Flatten Binary Tree to Linked List (LeetCode 114): Solution and Explanation
Rearrange a binary tree in place so that it becomes a chain of right pointers visiting the nodes in preorder. Every left pointer ends up null, and the same node objects are reused rather than copied.
Watch it run step by step
Try your own input and write the code →Intuition
The easiest correct answer is to run a preorder traversal, store the nodes in a list, and then relink them one after another, setting each node's left to null and its right to the next node. That is O(n) time but also O(n) extra memory, and the problem invites you to do better.
Look at what preorder means locally. For a node curr, the order is curr, then its entire left subtree, then its entire right subtree. In the flattened list, the left subtree has to slide into the right slot, and the old right subtree has to hang off the very last node of the left subtree in preorder.
Which node is last in preorder within the left subtree? It is the rightmost node you reach by starting at curr.left and following right pointers as far as possible. Call it the runner. If you attach the old right subtree to runner.right, then move the left subtree over to curr.right and clear curr.left, the node curr is now in its final shape and nothing about the relative preorder has changed.
Then you simply step to curr.right and repeat. Each step fixes one node without any recursion or stack, which is the same pointer-threading idea behind Morris traversal, and it gives O(1) extra space.
Approach: In-place rewiring (Morris style)
- Start with
curr = rootand loop whilecurris notNone. - If
curr.leftexists, setrunner = curr.leftand walkrunner = runner.rightuntilrunner.rightisNone. - Attach the original right subtree to the runner with
runner.right = curr.right. - Move the left subtree into the right slot with
curr.right = curr.left, then setcurr.left = None. - Whether or not there was a left child, advance with
curr = curr.rightand repeat until the chain ends.
Step-by-step example
root = [1,2,5,3,4,null,6]
- At node 1, the left child is 2. The runner starts at 2 and moves right to 4, the rightmost node of the left subtree.
- Set 4.right to 5 (the old right subtree of 1), then move 2 into 1.right and clear 1.left. The tree reads 1, 2, with 2 still having left 3 and right 4, and 4 now pointing to 5 and then 6.
- Advance to 2. Its left child is 3, which has no right child, so the runner stays at 3.
- Set 3.right to 4, move 3 into 2.right, and clear 2.left. The chain is now 1, 2, 3, 4, 5, 6.
- Nodes 3, 4, 5 and 6 have no left children, so the loop just walks down the right pointers and stops after 6. The result is [1,null,2,null,3,null,4,null,5,null,6].
Code: Python, Java, C++
1class Solution:
2 def flatten(self, root: Optional[TreeNode]) -> None:
3 """
4 Do not return anything, modify root in-place instead.
5 """
6 curr = root
7 while curr:
8 if curr.left:
9 runner = curr.left
10 while runner.right:
11 runner = runner.right
12
13 runner.right = curr.right
14 curr.right = curr.left
15 curr.left = None
16 curr = curr.right1class Solution {
2 public void flatten(TreeNode root) {
3 TreeNode curr = root;
4 while (curr != null) {
5 if (curr.left != null) {
6 TreeNode runner = curr.left;
7 while (runner.right != null) {
8 runner = runner.right;
9 }
10
11 runner.right = curr.right;
12 curr.right = curr.left;
13 curr.left = null;
14 }
15 curr = curr.right;
16 }
17 }
18}1class Solution {
2public:
3 void flatten(TreeNode* root) {
4 TreeNode* curr = root;
5 while (curr) {
6 if (curr->left) {
7 TreeNode* runner = curr->left;
8 while (runner->right) {
9 runner = runner->right;
10 }
11
12 runner->right = curr->right;
13 curr->right = curr->left;
14 curr->left = nullptr;
15 }
16 curr = curr->right;
17 }
18 }
19};Time and space complexity
O(n)
The outer loop visits each node once. The runner walks down right spines of left subtrees, and each of those edges is walked at most once before that part of the tree is folded into the final chain, so the total work is linear.
O(1)
Only the two pointers curr and runner are used. There is no recursion and no auxiliary stack or list.
Other approaches
Reverse preorder recursion (time O(n), space O(h))
Visit nodes in the order right, left, root while keeping a prev pointer to the node handled last. Each node sets right = prev and left = None, building the list from the tail backward. It is short and elegant but uses O(h) stack space.
Explicit stack preorder (time O(n), space O(h))
Push the root, then repeatedly pop a node, push its right child and then its left child, and link the popped node's right pointer to whatever is now on top of the stack. It is easy to reason about and avoids recursion limits.
Common mistakes
- Forgetting to set
curr.left = None. The checker expects every left pointer to be null, and leaving it creates a cycle when you later walk the list. - Overwriting
curr.rightbefore saving it torunner.right, which loses the entire right subtree. - Finding the runner by going left instead of right. The last preorder node of the left subtree is its rightmost node along right pointers only.
- Returning a new list or a new root. The function must modify the tree in place and return nothing.
Frequently asked questions
Can you flatten a binary tree with O(1) extra space?
Yes. For each node with a left child, find the rightmost node of that left subtree, hang the right subtree off it, and move the left subtree to the right. This needs only a couple of pointers and no recursion.
Why is the in-place flatten O(n) when it has a nested loop?
The inner loop only walks right pointers inside a left subtree, and once that subtree is moved into the chain those edges are never walked by a runner again. Summed over the whole run, the inner loop does O(n) steps.
Why does the flattened order have to be preorder?
That is how the problem defines the result. Preorder works naturally here because a node comes before both its subtrees, so each node can be finalized as soon as the loop reaches it.