Given a binary tree, print its nodes level by level in spiral order, i.e., all nodes present at level 1 should be printed first from left to right, followed by nodes of level 2 from right to left, followed by nodes of level 3 from left to right and so on… In other words, odd levels should be printed from left to right, and even levels should be printed from right to left or vice versa.

For example, the spiral level order traversal for the following tree is

(1, 3, 2, 4, 5, 6, 7) or (1, 2, 3, 7, 6, 5, 4)
 

Level Order Traversal

Practice this problem

 
A simple solution is to print all nodes of level 1 first, followed by level 2, … till level h, where h is the tree’s height. We can print all nodes present in a level by modifying the preorder traversal on the tree. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

15 20 10 8 12 16 25

Java


Download  Run Code

Output:

15 20 10 8 12 16 25

Python


Download  Run Code

Output:

15 20 10 8 12 16 25

The time complexity of the above solution is O(n2), where n is the total number of nodes in the binary tree.

 
We can reduce the time complexity to O(n) by using extra space. Following is a pseudocode for a simple queue-based spiral order traversal:

levelorder(root)
q —> empty double ended queue
q.push(root)
while (not q.isEmpty())
  while (level is even)
    node —> q.popFront()
    visit(node)
    if (node.left <> null)
      q.pushBack(node.left)
    if (node.right <> null)
      q.pushBack(node.right)
 
  while (level is odd)
    node —> q.popBack()
    visit(node)
    if (node.right <> null)
      q.pushFront(node.right)
    if (node.left <> null)
      q.pushFront(node.left)

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

15
20 10
8 12 16 25

Java


Download  Run Code

Output:

15
20 10
8 12 16 25

Python


Download  Run Code

Output:

15
20 10
8 12 16 25

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.

 
We can also solve this problem by using hashing. The following code traverses the tree in a preorder fashion and uses a map to store every node and its level using the level number as a key. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Level 1: 15
Level 2: 20 10
Level 3: 8 12 16 25
Level 4: 30 20

Java


Download  Run Code

Output:

Level 1: 15
Level 2: 20 10
Level 3: 8 12 16 25
Level 4: 30 20

Python


Download  Run Code

Output:

Level 1: [15]
Level 2: [20, 10]
Level 3: [8, 12, 16, 25]
Level 4: [30, 20]

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.