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