Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.
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
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level order traversal, keep track of previous node. Make current node as right child of previous and left of previous node as NULL. This solution requires queue, but question asks to solve without additional data structure.
Efficient Without Additional Data StructureRecursively look for the node with no grandchildren and both left and right child in the left sub-tree. Then store node->right in temp and make node->right=node->left. Insert temp in first node NULL on right of node by node=node->right. Repeat until it is converted to linked list.
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Flatten a binary tree into linked list | Set-3
- Flatten a binary tree into linked list | Set-2
- Flatten a multilevel linked list
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Create a sorted linked list from the given Binary Tree
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Construct Complete Binary Tree from its Linked List Representation
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Flatten a multi-level linked list | Set 2 (Depth wise)
- Flatten Binary Tree in order of Zig Zag traversal
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Flatten Binary Tree in order of Level Order Traversal
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : Spider_man