Spiral traversal of binary tree

Given a binary tree , print it’s nodes in spiral fashion. Example for Given Tree,Output should be F,B,G,I,D,A,C,E,H

This is also called zig zag tree traversal.


Algorithm :
We usually use a queue for level order traversal of a queue. If we want to use the same here, how will we change direction of traversal on every alternate level?
If we think logically then we will see that we need stack in place of queue. Now again a single stack won’t serve our purpose here, we need 2 stacks: One stack for printing node from left to right and one stack for printing node from right to left. Note that for printing node from left to right,right node has to be push first into stack. All nodes of one level are put in either one of these stacks.

In the code given below, stack1 has been used for printing nodes from right to left and stack2 has been used for printing nodes from left to right.

void spiralLevelOrderTraversal(struct node *root)

	stack stack1;
	stack stack2;


	while (stack1.empty() == false || stack2.empty() == false)
		while (stack1.empty() == false)
			struct node *node = stack1.top();
			cout << node->data << " "; 			


		while (stack2.empty() == false)

			struct node *node = stack2.top();
			cout << node->data << " "; 			

Time Complexity : O(n)

4 Thoughts on “Spiral traversal of binary tree

  1. The line on line# 29 should be stack2.pop()

  2. Pingback: Recursive Spiral Order Traversal of Tree

  3. Instead use the approach for level order traversal using a queue; however, instead of printing store the nodes (in a vector) at each level till the level is complete. Then print them in spiral order (from beginning or end of vector as is the case)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation