Given a binary tree, flatten it into a linked list. After flattening, the left of each node should point to NULL and right should contain next node in level order.
Input: 1 / \ 2 5 / \ \ 3 4 6 Output: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Input: 1 / \ 3 4 / 2 \ 5 Output: 1 \ 3 \ 4 \ 2 \ 5
Approach: An approach using recursion has already been discussed in the previous post. A pre-order traversal of the binary tree using stack has been implied in this approach. In this traversal, every time a right child is pushed in the stack, the right child is made equal to the left child and left child is made equal to NULL. If the right child of the node becomes NULL, the stack is popped and the right child becomes the popped value from the stack. The above steps are repeated until the size of the stack is zero or root is NULL.
Below is the implementation of the above approach:
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Time Complexity: O(N)
Auxiliary Space: O(Log N)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Flatten a binary tree into linked list | Set-3
- Flatten a binary tree into linked list
- Flatten a multilevel linked list
- Create a sorted linked list from the given Binary Tree
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Construct Complete Binary Tree from its Linked List Representation
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Flatten a multi-level linked list | Set 2 (Depth wise)
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Flatten binary tree in order of post-order traversal
- Linked complete binary tree & its creation
- Decimal Equivalent of Binary Linked List
- Binary Search on Singly Linked List
- Create a Doubly Linked List from a Ternary Tree
- Flatten BST to sorted list | Decreasing order
- Flatten BST to sorted list | Increasing order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.