![]() |
VOOZH | about |
Perfect Binary Tree using Specific Level Order Traversal in Set 1. The earlier traversal was from Top to Bottom. In this post, Bottom to Top traversal (asked in Amazon Interview | Set 120 – Round 1) is discussed.
16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 8 15 9 14 10 13 11 12 4 7 5 6 2 3 1
The task is to print nodes in level order but nodes should be from left and right side alternatively and from bottom – up manner
5th level: 16(left), 31(right), 17(left), 30(right), … are printed. 4th level: 8(left), 15(right), 9(left), 14(right), … are printed. v 3rd level: 4(left), 7(right), 5(left), 6(right) are printed. 1st and 2nd levels are trivial.
Approach 1:
The standard level order traversal idea slightly changes here.
Implementation:
Specific Level Order traversal of binary tree is 2 3 1
Time complexity: O(n), the time complexity of the above program is O(n) as we traverse each node of the tree exactly once.
Auxiliary Space: O(n), we use a queue and a stack to store the nodes of the tree, which makes the space complexity of the program O(n).
Approach 2: (Using vector)
Implementation:
Specific Level Order traversal of binary tree is 2 3 1
Time Complexity: O(n), as we are traversing each node of the binary tree once.
Auxiliary Space: O(n), as we are storing the nodes of each level in a vector and pushing them in a stack.