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
- Flatten a binary tree into linked list | Set-2
- Flatten a multilevel linked list
- Flatten a multi-level linked list | Set 2 (Depth wise)
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Construct Complete Binary Tree from its Linked List Representation
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Create a Doubly Linked List from a Ternary Tree
- Binary Search on Singly Linked List
- Decimal Equivalent of Binary Linked List
- Linked complete binary tree & its creation
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.