Write a function to print ZigZag order traversal of a binary tree. For the below binary tree the zigzag order traversal will be 1 3 2 7 6 5 4
This problem can be solved using two stacks. Assume the two stacks are current: currentlevel and nextlevel. We would also need a variable to keep track of the current level order(whether it is left to right or right to left). We pop from the currentlevel stack and print the nodes value. Whenever the current level order is from left to right, push the nodes left child, then its right child to the stack nextlevel. Since a stack is a LIFO(Last-In-First_out) structure, next time when nodes are popped off nextlevel, it will be in the reverse order. On the other hand, when the current level order is from right to left, we would push the nodes right child first, then its left child. Finally, do-not forget to swap those two stacks at the end of each level(i.e., when current level is empty)
Below is the implementation of the above approach:
ZigZag Order traversal of binary tree is 1 3 2 7 6 5 4
Time Complexity: O(n)
Space Complexity: O(n)+(n)=O(n)
Below is a simple implementation of this problem.
Level order traversal in spiral form
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Reverse zigzag Traversal of a Binary Tree
- Zigzag (or diagonal) traversal of Matrix
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Level order traversal of Binary Tree using Morris Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Cartesian tree from inorder traversal | Segment Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- If you are given two traversal sequences, can you construct the binary tree?
- Level Order Tree Traversal
- Inorder Tree Traversal without Recursion
- Inorder Tree Traversal without recursion and without stack!
- Construct Special Binary Tree from given Inorder traversal
- Construct a special tree from given preorder traversal
- Boundary Traversal of binary tree
- Perfect Binary Tree Specific Level Order Traversal
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Diagonal Traversal of Binary Tree