Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.
Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5
Approach: We will solve this problem by simulating the Level order traversal of Binary Tree as follows:
- Create a queue to store the nodes of Binary tree.
- Create a variable “prev” and initialise it by parent node.
- Push left and right children of parent in the queue.
- Apply level order traversal. Lets say “curr” is front most element in queue. Then,
- If ‘curr’ is NULL, continue.
- Else push curr->left and curr->right in the queue
- Set prev = curr
Below is the implementation of the above approach:
1 5 2 6 4 9 3
Time Complexity: O(N)
Space Complexity: O(N) where N is the size of Binary Tree.
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 binary tree in order of post-order traversal
- Level order traversal of Binary Tree using Morris Traversal
- Flatten Binary Tree in order of Zig Zag traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Insertion in n-ary tree in given order and Level order traversal
- Connect Nodes at same Level (Level Order Traversal)
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Build Binary Tree from BST such that it's level order traversal prints sorted data
- Density of Binary Tree using Level Order Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Check if the level order traversal of a Binary Tree results in a palindrome
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Boundary Level order traversal of a Binary Tree
- Specific Level Order Traversal of Binary Tree
- Level Order Tree Traversal
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Zig Zag Level order traversal of a tree using single array
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.