Flatten Binary Tree to Linked List

Medium

Description

Flatten a binary tree to a linked list in-place, following pre-order traversal. Right child points to next node.

Examples

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

Pre-order: 1,2,3,4,5,6 as linked list.

Input:root = [7,3,11,1,null,9,13]
Output:[7,null,3,null,1,null,11,null,9,null,13]
Explanation:

Pre-order traversal visits nodes in order: root, left subtree, right subtree. Starting from 7, visiting left child 3, then its left child 1. After exhausting left subtree, visiting right subtree starting with 11, then its left child 9, and finally right child 13.

Input:root = [5]
Output:[5]
Explanation:

Single node tree remains unchanged. The root has no children, so the flattened result is just the single node with no right pointer needed.

Constraints

  • 0 ≤ number of nodes ≤ 2000

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!