 All Problems
Flatten Binary Tree to Linked List
medium
tree
depth-first search
stack
linked list
binary tree
amazon
microsoft
facebook

Given the root of a binary tree, flatten the tree into a "linked list": the right child always points to the next node of a preorder traversal, and the left child is always null. Do it in-place.

Example 1:

Input:  1 2 5 3 4 null 6
Output: 1 2 3 4 5 6
(as a right-skewed tree: 1→2→3→4→5→6)

Example 2:

Input:  0
Output: 0

Constraints:

  • The number of nodes is in the range [0, 2000]
  • -100 ≤ Node.val ≤ 100

Input format: BFS level-order, space-separated, null for missing nodes.

Output format: Space-separated values in the flattened order (preorder).

Run to check your code against the sample cases, or submit to run every case