Flatten Binary Tree to Linked List - Problem
Given the root of a binary tree, flatten the tree into a "linked list":
- The "linked list" should use the same
TreeNodeclass where the right child pointer points to the next node in the list and the left child pointer is alwaysnull. - The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Note: The transformation should be done in-place - modify the original tree structure rather than creating a new tree.
Input & Output
Example 1 — Basic Binary Tree
$
Input:
root = [1,2,5,3,4,null,6]
›
Output:
[1,2,3,4,5,6]
💡 Note:
Pre-order traversal gives us 1→2→3→4→5→6. The flattened tree becomes a right-skewed tree with this sequence.
Example 2 — Empty Tree
$
Input:
root = []
›
Output:
[]
💡 Note:
Empty tree remains empty after flattening.
Example 3 — Single Node
$
Input:
root = [0]
›
Output:
[0]
💡 Note:
Single node tree remains unchanged - no left or right children to rearrange.
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -100 ≤ Node.val ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code