Flatten Binary Tree to Linked List - Problem
Transform a Binary Tree into a Flattened Linked List
Given the
Requirements:
• Use the same
• Set all
• Use
• Follow pre-order traversal order (root → left subtree → right subtree)
Example: A tree like
This problem tests your understanding of tree traversal, in-place modification, and space optimization techniques.
Given the
root of a binary tree, your task is to flatten the tree into a "linked list" structure. This isn't a traditional linked list - instead, you'll modify the existing tree nodes to form a right-skewed tree that resembles a linked list.Requirements:
• Use the same
TreeNode class (no new data structure)• Set all
left child pointers to null• Use
right child pointers to connect to the next node• Follow pre-order traversal order (root → left subtree → right subtree)
Example: A tree like
[1,2,5,3,4,null,6] becomes a right-skewed "linked list": 1→2→3→4→5→6This problem tests your understanding of tree traversal, in-place modification, and space optimization techniques.
Input & Output
example_1.py — Basic Binary Tree
$
Input:
root = [1,2,5,3,4,null,6]
›
Output:
[1,null,2,null,3,null,4,null,5,null,6]
💡 Note:
The original tree has root 1 with left child 2 and right child 5. Node 2 has children 3 and 4, node 5 has child 6. After flattening in pre-order (1→2→3→4→5→6), all nodes are connected via right pointers forming a right-skewed tree.
example_2.py — Single Node
$
Input:
root = [0]
›
Output:
[0]
💡 Note:
A tree with only one node remains unchanged after flattening, as there are no other nodes to connect.
example_3.py — Empty Tree
$
Input:
root = []
›
Output:
[]
💡 Note:
An empty tree (null root) remains empty after the flattening operation.
Time & Space Complexity
Time Complexity
O(n)
Each node is pushed and popped from stack exactly once, making it linear time
✓ Linear Growth
Space Complexity
O(h)
Stack space proportional to tree height: O(log n) for balanced trees, O(n) worst case for skewed trees
✓ Linear Space
Constraints
-
The number of nodes in the tree is in the range
[0, 2000] -
-100 ≤ Node.val ≤ 100 -
Follow up: Can you flatten the tree in-place (with
O(1)extra space)?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code