151. Flatten Binary Tree to Linked List

Medium · Binary Tree

Given the root of a binary tree, flatten the tree in-place into a linked list using the right pointers. The linked list should follow a pre-order traversal of the original tree.

After flattening, the tree structure should have all nodes in a single chain where each node's left pointer is null and the right pointer points to the next node in pre-order sequence.

Examples

Example 1
Input: [1, 2, 5, 3, 4, null, 6]
Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6]
Explanation: The binary tree is flattened to a linked list. Pre-order traversal is: 1 → 2 → 3 → 4 → 5 → 6. Each node's left becomes null, and right points to the next node in the sequence.
Example 2
Input: [1]
Output: [1]
Explanation: A single node tree is already flattened.

Constraints