Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Flatten a binary tree to a linked list

Transform a binary tree into a right-skewed linked list in-place following preorder traversal.

Python practice30 minTrees & Binary TreesAdvancedLast updated March 29, 2026

Problem statement

Given the root of a binary tree, flatten the tree into a 'linked list': the left child pointer of every node should be set to None and the right child pointer should point to the next node in the list. The order of nodes in the linked list must match the preorder traversal of the original tree (root, left, right). You must modify the tree in-place without creating new tree nodes. Provide a function flatten(root) that transforms the tree. For testing convenience, helper functions are provided to build a tree from a level-order list and to return the flattened node values as a Python list by following right pointers from the root.

Task

Implement an in-place algorithm that flattens a binary tree into a singly linked list using only right pointers, following preorder traversal (root, left, right).

Examples

Example

Input

[1, 2, 5, 3, 4, None, 6]

Output

[1, 2, 3, 4, 5, 6]

Original tree (level-order): [1,2,5,3,4,None,6]. Preorder traversal is [1,2,3,4,5,6]. After flattening, the tree becomes a right-skewed list 1 -> 2 -> 3 -> 4 -> 5 -> 6.

Input format

A level-order list representation of the binary tree, where None represents a missing child. Tests call the helper flatten_and_list(level_list).

Output format

A Python list of node values representing the flattened tree when traversed via right pointers from the root.

Constraints

0 <= number of nodes <= 10^4; node values are integers. Must perform transformation in-place (no new TreeNode instances for original nodes).

Samples

Sample 1

Input

[1, 2, 5, 3, 4, None, 6]

Output

[1, 2, 3, 4, 5, 6]

See example above. The flattened list follows preorder traversal.