VOOZH about

URL: https://www.geeksforgeeks.org/dsa/perfect-binary-tree-specific-level-order-traversal-set-2/

⇱ Perfect Binary Tree Specific Level Order Traversal | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perfect Binary Tree Specific Level Order Traversal | Set 2

Last Updated : 23 Jul, 2025

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.

👁 image(4)

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. 

  1. Instead of processing ONE node at a time, we will process TWO nodes at a time.
  2. For dequeued nodes, we push node’s left and right child into stack in following manner - 2nd node’s left child, 1st node’s right child, 2nd node’s right child and 1st node’s left child.
  3. And while pushing children into queue, the enqueue order will be: 1st node’s right child, 2nd node’s left child, 1st node’s left child and 2nd node’s right child. Also, when we process two queue nodes.
  4. Finally pop all Nodes from stack and prints them.

Implementation:


Output
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) 

  1. We will traverse each level top to down and we will push each level to stack from top to down 
  2. so, that we can have finally down to up printed levels, 
  3. we are having a level in a vector so we can print it in any defined way, 

Implementation:


Output
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.

Comment
Article Tags: