Given a perfect binary tree, print the values of alternating left and right nodes for each level in a top-down and bottom-up manner.

For example, there are two ways to print the following tree:
 

Variation 1: Print Top-Down

(1, 2, 3, 4, 7, 5, 6, 8, 15, 9, 14, 10, 13, 11, 12)
 

Variation 2: Print Bottom-Up

(8, 15, 9, 14, 10, 13, 11, 12, 4, 7, 5, 6, 2, 3, 1)

 
Perfect Binary Tree

Variation 1: Print Top-Down

Practice this problem

The idea is to modify level order traversal by maintaining two queues. We process two nodes each from one queue and enqueue the left and right child of the first popped node into the first queue and the right and left child of the second popped node into the second queue.

Following is the C++, Java, and Python implementation based on the above idea:

C++


Download  Run Code

Output:

1 2 3 4 7 5 6 8 15 9 14 10 13 11 12

Java


Download  Run Code

Output:

1 2 3 4 7 5 6 8 15 9 14 10 13 11 12

Python


Download  Run Code

Output:

1 2 3 4 7 5 6 8 15 9 14 10 13 11 12

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.

Variation 2: Print Bottom-Up

Practice this problem

The idea is to store nodes of every level in the desired order in a map and finally print nodes from the map for each level, starting from the last level to the first level.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

8 15 9 14 10 13 11 12 4 7 5 6 2 3 1

Java


Download  Run Code

Output:

[8, 15, 9, 14, 10, 13, 11, 12][4, 7, 5, 6][2, 3][1]

Python


Download  Run Code

Output:

[8, 15, 9, 14, 10, 13, 11, 12][4, 7, 5, 6][2, 3][1]

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the binary tree.

 
Exercise: Modify the solution to print using only one queue