ExamAdda Logo

Flatten Binary Tree to Linked List

Easy

Given the root of a binary tree, flatten the tree into a linked list in-place.

The linked list should use the same TreeNode structure:

  • The right pointer points to the next node.
  • The left pointer of every node must be nullptr.
  • The nodes must follow preorder traversal.

Example 1

Input

root = [1,2,5,3,4,null,6]

Output

1 2 3 4 5 6

Explanation

The preorder traversal is 1 → 2 → 3 → 4 → 5 → 6. The tree is rearranged so that these nodes form a linked list using only right pointers.

Example 2

Input

root = []

Output

[]

Explanation

The tree is empty, so there is nothing to flatten.

Constraints

0 <= number of nodes <= 2000
-100 <= Node.val <= 100

Hints:

Hint 1

The flattened list must follow the preorder traversal of the original tree.

Hint 2

For each node, move its left subtree between the node and its original right subtree, then continue with the right pointer.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 18, 2026

Last updated

Aug 19, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output