mediumTreeTrees

Flatten Binary Tree to Linked List

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

Recognize the pattern

flatten tree into right-skewed listin preorderin-place

Brute force idea

If you approach Flatten Binary Tree to Linked List in the most literal way possible, you get this: 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.

Better approach

A calmer way to see Flatten Binary Tree to Linked List is this: 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.

Key invariant

The truth you want to protect throughout Flatten Binary Tree to Linked List is this: 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.

Watch out for

A common way to get lost in Flatten Binary Tree to Linked List is this: 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