Level order traversal in spiral form | Using one stack and one queue

Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
Spiral image
You are allowed to use only one stack.

We have seen recursive and iterative solutions using two stacks . In this post, a solution with one stack and one queue is discussed. The idea is to keep on entering nodes like normal level order traversal, but during printing, in alternative turns push them onto the stack and print them, and in other traversals, just print them the way they are present in the queue.

Following is the CPP implementation of the idea.





// CPP program to print level order traversal
// in spiral form using one queue and one stack.
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *left, *right;
/* Utility function to create a new tree node */
Node* newNode(int val)
    Node* new_node = new Node;
    new_node->data = val;
    new_node->left = new_node->right = NULL;
    return new_node;
/* Function to print a tree in spiral form 
   using one stack */
void printSpiralUsingOneStack(Node* root)
    if (root == NULL)
    stack<int> s; 
    queue<Node*> q;
    bool reverse = true;
    while (!q.empty()) {
        int size = q.size();
        while (size) {
            Node* p = q.front();
            // if reverse is true, push node's 
            // data onto the stack, else print it
            if (reverse)
                cout << p->data << " ";
            if (p->left)
            if (p->right)
        // print nodes from the stack if 
        // reverse is true
        if (reverse) {
            while (!s.empty()) {
                cout << s.top() << " ";
        // the next row has to be printed as 
        // it is, hence change the value of 
        // reverse
        reverse = !reverse;
/*Driver program to test the above functions*/
int main()
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(7);
    root->left->right = newNode(6);
    root->right->left = newNode(5);
    root->right->right = newNode(4);
    return 0;



1 2 3 4 5 6 7

Time Complexity : O(n)
Auxiliary Space : O(n)

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.