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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Inorder traversal of an N-ary Tree
- Vertical Zig-Zag traversal of a Tree
- DFS traversal of a tree using recursion
- Zig-Zag traversal of a Binary Tree using Recursion
- Boundary Traversal of binary tree
- Preorder Traversal of N-ary Tree Without Recursion
- Inorder Tree Traversal without Recursion
- Level Order Tree Traversal
- Iterative Preorder Traversal of an N-ary Tree
- Density of Binary Tree in One Traversal
- Iterative Postorder Traversal of N-ary Tree
- Diagonal Traversal of Binary Tree
- Clockwise Triangular traversal of a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.