Given a Binary Tree, the task is to perform Specific Level Order Traversal of the tree such that at each level print 1st element then the last element, then 2nd element and 2nd last element, until all elements of that level is printed and so on.
Approach: The idea is to the Level Order Traversal of the given Binary Tree and convert this tree into Perfect Binary Tree. While traversing if any node whose child Node doesn’t exist then append NULL node as the child node in the queue. Below are the steps:
- Perform the level order traversal of the given tree.
- During traveral if any node whose child Node doesn’t exist then append NULL node as the child node in the queue
- During traversal for each level do the following:
- Maintain two queues to store the nodes for the two half of each level.
- For first half of the level store nodes in left to right manner.
- For second half of the level store nodes in right to left manner.
- Iterate the above two queues formed and print in an alternate manner for specific level order traversal.
Below is the implementation of the above approach:
1 2 3 4 7 5 8 15 9 14 10 11 16 31 17 30 18 29 19 28 20 21 22 23
Time Complexity: O(N), N is the number of nodes
Auxiliary Space: O(N), N is the number of nodes
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.
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Level order traversal of Binary Tree using Morris Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Density of Binary Tree using Level Order Traversal
- Boundary Level order traversal of a Binary Tree
- Deletion of a given node K in a 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
- 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
- Insertion in n-ary tree in given order and Level order traversal
- Level Order Tree Traversal
- Zig Zag Level order traversal of a tree using single array
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Flatten binary tree in order of post-order traversal
- Mix Order Traversal of a Binary Tree
- Insertion in a Binary Tree in level order