Algorithm-Day47-Flatten-Binary-Tree-to-Linked-List-lc-114
🧩 Problem Description
Given the root
of a binary tree, flatten it to a linked list in-place.
The linked list should follow the same order as a pre-order traversal.
💬 Example
1 | Input: root = [1,2,5,3,4,null,6] |
💡 Approach 1: Reverse Preorder DFS
We can do a reverse preorder traversal (right → left → root) and keep track of the previous node to build the flattened list.
🔢 Java Code
1 | class Solution { |
💡 Approach 2: Iterative with Stack
We can also simulate preorder traversal using a stack and rearrange pointers.
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n) — visiting all nodes once.
- Space Complexity: O(h) for recursion / stack (O(n) in worst case).
✍️ Summary
- Reverse preorder DFS is a neat trick because it avoids extra temporary storage.
- Iterative stack solution is more explicit and easier to debug.
- Related problems:
lc-116
— Populating Next Right Pointers in Each Nodelc-430
— Flatten a Multilevel Doubly Linked List