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 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: Recurse the binary tree in Inorder Format, at every stage of function call pass on the address of last node in the flattened linked list so that current node can make itself a right node of the last node.
For left child, it’s parent node is the last node in the flattened list
For the right child there are two conditions:
- If there is no left child to the parent, parent node is the last node in the flattened list.
- If left child is not null then leaf node from left sub-tree is the last node in the flattened list.
Below is the implementation of the above approach:
Original inorder traversal : 3 2 4 1 5 6 Flattened inorder traversal : 1 2 3 4 5 6
- Flatten a binary tree into linked list | Set-2
- Flatten a binary tree into linked list
- 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
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Flatten a multi-level linked list | Set 2 (Depth wise)
- Construct Complete Binary Tree from its Linked List Representation
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- 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
- Binary Search on Singly Linked List
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.