Level order traversal in spiral form
Write a program to print Level Order Traversal in spiral form of a binary tree.
Example:

For the above tree:
Basic level order traversal:
2
7 5
2 6 9
5 11 4
Level order traversal in spiral form:
2
7 5 (left to right)
9 6 2 (right to left)
5 11 4 (again left to right)
The solution will, of course, surround basic level order traversal. The spiral order means - It will go from left to right for one level, then right to left for next level and again left to right for the next one and so on.
We need to modify our basic level order traversal.
We can do the flipping of direction (left → right then right → left so on ...) by keeping a flag variable which will be updated at end of each level.
Pre-requisite: Root to tree
1. Declare flag as 1(true); 2. Declare a queue q to store pointer to nodes(node*); 3. Declare a stack s which helps us for flipping. 4. Print the root as we are not going to bother about root level; 5. IF(root->left) //left child exists ENQUEUE(q, root->left); END IF IF(root->right) //right child exists ENQUEUE(q, root->right); END IF IF root has no child RETURN BACK //nothing to print more ELSE q.push(NULL); //to indicate end of 1st level 6. //Here goes the modified level order traversal When flag=1 its left-to right flag=0 its right to left while (q is not empty){ temp=DEQUEUE(q); IF(temp==NULL) //end of last traversed level IF (q is not empty) ENQUEUE (q, NULL); END IF IF (flag==0) Pop and print data from stack until stack is empty END IF flag=1-flag; //flip flag for next level 1 to 0 or 0 to 1 ELSE IF(flag == 1) Print temp->data; //left to right printing ELSE Push temp->data to stack s; //this makes right to left //printing as rightmost node will be at the top of stack END IF-ELSE // basic level order traversal (direction left to right) IF(root->left) //left child exists ENQUEUE(q, root->left); END IF IF (root->right) //right child exists ENQUEUE(q, root->right); END IF END IF-ELSE (outer one) END WHILE loopExample with Explanation:
For the above tree root is being printed first without any constraint 2 For the first level flag is 1 Thus it prints immediately while accessing temp node 7 5 (since basic traversal direction is always left to right) At the end of level flag flips to 0 So while traversing instead of printing nodes at once, nodes get stored in stack At the end of level all the nodes data being popped and printed. In stack 9(top) 6 2 Thus printing 9 6 2 (right to left) Flag again flipped to 1 Basic left to right printing 5 11 4 So the output is in spiral orderC++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer