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 TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • 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
INPUT TREEALGORITHMRESULT1253461Find Rightmost2Connect to Right3Move Left → Right4Continue Process123456Pre-order: 1→2→3→4→5→6Key Insight:Connect rightmost node of left subtree to right subtree, then move left subtree to right positionTutorialsPoint - Flatten Binary Tree to Linked List | DFS Approach
Asked in
Facebook 45 Microsoft 38 Amazon 32 Google 28
52.0K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen