You are given the root of a binary tree. Rearrange it, in place, into a chain that looks like a linked list built from the same tree nodes.
In the chain every node's left child is null and its right child is the next node. The nodes must appear in preorder: a node first, then everything in its left subtree, then everything in its right subtree. The function returns nothing; the tree itself is changed.
Example 1
Input: root = [7, 2, 9, 1, 4, null, 8] Output: [7, null, 2, null, 1, null, 4, null, 9, null, 8] Why: preorder is 7, 2, 1, 4, 9, 8, each one hung on the right
2 more examples and the constraints
Example 2
Input: root = [6, 1] Output: [6, null, 1] Why: the only left child moves to the right
Example 3
Input: root = [] Output: [] Why: an empty tree stays empty
Constraints
- 0 ≤ number of nodes ≤ 2,000
- −100 ≤ each node's value ≤ 100
- Follow-up: can you do it with O(1) extra memory?
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect preorder, then relinkO(n)
- Splice in placeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 nodes | Verdict |
|---|---|---|---|
| Collect preorder, then relink | O(n) | Passes; uses O(n) memory | |
| Splice in place | O(n) | Best; meets the O(1) follow-up |
n = number of nodes in the tree. Both are linear; they differ in memory.
Edge cases to test
- Empty tree. root is null: there is nothing to do and nothing to return.
- Already a chain. [3, null, 5] has no left links, so it must come out unchanged.
- Only left children. [1, 2, null, 3] turns into a right chain 1 → 2 → 3, with depth 2,000 in the worst case.
- Right subtree must survive. Moving the left subtree over must not drop the old right subtree; it goes under the rightmost left node.
Common mistakes
- Setting
cur.right = cur.leftbefore saving the oldcur.right, which loses the right subtree. - Forgetting to set
leftto null, so the result still looks like a tree. - Using plain recursion on a 2,000-deep tree in a language with a small call stack.
How to talk through it
- 1Clarify. Must it be in place? Is the order preorder? Can the tree be empty or very deep?
- 2Give the simple version. Collect the nodes in preorder, then relink them: O(n) time and O(n) space.
- 3Name the key fact. In preorder,
cur.rightcomes right after the rightmost node ofcur's left subtree. - 4Code the splice. Find that node, hang
cur.rightunder it, move left to right, clear left, step right. - 5Test out loud. Run an empty tree, a left-only chain and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?