mediumTreeTrees

Flatten Binary Tree to Linked List

mediumTime: O(n)Space: O(1)

Signals to notice

flatten tree into right-skewed listin preorderin-place

Brute force first

Preorder traversal to array, build linked list from array. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

For each node, find the rightmost node of its left subtree. Set that node's right to the current node's right. Then move the left subtree to the right and null out left. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The left subtree's rightmost node connects to the current right subtree. This preserves preorder: root → left subtree → right subtree, all linked via right pointers. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Losing the right subtree reference — save it BEFORE overwriting the right pointer with the left subtree. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Trees Pattern