Given a Complete Binary Tree, the task is to print the elements in the following pattern. Let's consider the tree to be:
👁 Image
The tree is traversed in the following way:
👁 Image
The output for the above tree is:
1 3 7 11 10 9 8 4 5 6 2
Approach: The idea is to use the modified breadth first search function to store all the nodes at every level in an array of vector. Along with it, the maximum level up to which the tree needs to be traversed is also stored in a variable. After this precomputation task, the following steps are followed to get the required answer:
- Create a vector tree[] where tree[i] will store all the nodes of the tree at the level i.
- Take an integer variable k which keeps the track of the level number that is being traversed and another integer variable path which keeps the track of the number of cycles that have been completed. A flag variable is also created to keep the track of the direction in which the tree is being traversed.
- Now, start printing the rightmost nodes at each level until the maximum level is reached.
- Since the maximum level is reached, the direction has to be changed. In the last level, print elements from rightmost to left. And the value of maxLevel variable has to be decremented.
- As the tree is being traversed from the lower level to the upper level, the rightmost elements are printed. Since in the next iteration, the maxlevel value has been changed, it makes sure that already visited nodes in the last level are not traversed again.
Below is the implementation of the above approach:
Output: 1 3 7 11 10 9 8 4 5 6 2