![]() |
VOOZH | about |
Given a Perfect Binary Tree like below:
Print the level order of nodes in following specific manner:
1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24
i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5(left), 6(right) are printed. While 4th level: 8(left), 15(right), 9(left), 14(right), .. are printed. While 5th level: 16(left), 31(right), 17(left), 30(right), .. are printed.
We strongly recommend to minimize your browser and try this yourself first.
In standard Level Order Traversal, we enqueue root into a queue 1st, then we dequeue ONE node from queue, process (print) it, enqueue its children into queue. We keep doing this until queue is empty.
Approach 1: We can do standard level order traversal here too but instead of printing nodes directly, we have to store nodes in current level in a temporary array or list 1st and then take nodes from alternate ends (left and right) and print nodes. Keep repeating this for all levels.
This approach takes more memory than standard traversal.
Specific Level Order traversal of binary tree is 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue and vector data structure.
Approach 2: The standard level order traversal idea will slightly change here. Instead of processing ONE node at a time, we will process TWO nodes at a time. And while pushing children into queue, the enqueue order will be: 1st node's left child, 2nd node's right child, 1st node's right child and 2nd node's left child.
Implementation:
Specific Level Order traversal of binary tree is 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24
Time Complexity: O(n) where n is the total number of nodes in the tree.
Auxiliary Space : O(n)
Followup Questions: