114. Flatten Binary Tree to Linked List
mediumRewire a binary tree in place so every node's left is null and right follows a preorder traversal. The reverse-postorder twist solves it without extra storage — a classic in-place tree transform.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, flatten the tree into a 'linked list': the linked list should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The linked list should be in the same order as a preorder traversal of the binary tree.
Constraints
The number of nodes in the tree is in the range [0, 2000].-100 <= Node.val <= 100
Examples
Example 1
root = [1,2,5,3,4,null,6][1,null,2,null,3,null,4,null,5,null,6]Example 2
root = [][]Example 3
root = [0][0]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Preorder is root, left subtree, right subtree — so the flattened list goes node, then the flattened left, then the flattened right.
Hint 2
If you flatten in reverse-postorder (right, left, root) and keep a running 'prev' pointer, you can splice as you go.
Hint 3
Iterative without recursion: at each node, find the rightmost node of its left subtree and graft the current right onto it. Then move left to right and null out left. Repeat.
Solution approach
Reveal approach
Two clean options. (1) Reverse-postorder recursion: walk right, then left, then root, tracking prev (initially null). At each node: node.right = prev; node.left = null; prev = node. This rewrites pointers safely because each subtree is processed before its parent. (2) Iterative O(1) extra space: while curr is not null, if curr.left is not null, find rightmost = curr.left while walking right pointers; set rightmost.right = curr.right; set curr.right = curr.left; set curr.left = null. Move curr = curr.right. This grafts the left subtree into the right chain and nulls the left at each step. O(n) time. Recursive uses O(h) stack; iterative is O(1) extra space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- tree-dfs
- recursion
- linked-list
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
- Microsoft
- Bloomberg
More Trees practice problems
- 94. Binary Tree Inorder Traversal
- 98. Validate Binary Search Tree
- 100. Same Tree
- 101. Symmetric Tree
- 102. Binary Tree Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 104. Maximum Depth of Binary Tree
- 105. Construct Binary Tree from Preorder and Inorder Traversal