AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Flatten Binary Tree to Linked List

The key idea

The flattened order is exactly the preorder traversal (node, then left subtree, then right subtree). To do it in O(1) extra space, walk the tree and for each node that has a left child, find the rightmost node of that left subtree, hang the node's current right subtree off it, then move the whole left subtree over to the right side and clear left. This stitches each subtree into the chain in preorder without any recursion stack.

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

Examples

Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6]
Input: root = [] Output: []
Input: root = [0] Output: [0]

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems