Given a Binary Tree, the task is to print the zigzag order of the tree.
Input : 7 / \ 6 5 / / 4 3 / \ 2 1 Output : 7 5 6 4 3 1 2 Input : 1 / \ 2 3 / \ 4 5 Output : 1 3 2 4 5
We have already discussed the zigzag traversal using an iterative approach, in this post we will solve it using Recursion.
Recursive Approach: The idea is to traverse the tree in a Level Order manner but in a slightly different manner. We will use a variable flag and initially set it’s value to zero. As we complete the level order traversal of the tree, from right to left we will set the value of flag to one, so that next time we can traverse the Tree from left to right and as we complete the traversal we will set it’s value back to zero. We will repeat this whole step until we have traversed the Binary Tree completely.
Below is the implementation of the above approach:
7 5 4 9 10 11 6
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
- Postorder traversal of Binary Tree without recursion and without stack
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- ZigZag Tree Traversal
- DFS traversal of a tree using recursion
- Inorder Tree Traversal without Recursion
- Preorder Traversal of N-ary Tree Without Recursion
- Inorder Tree Traversal without recursion and without stack!
- Level order traversal of Binary Tree using Morris Traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Bottom View of a Binary Tree using Recursion
- Boundary Traversal of binary tree
- Density of Binary Tree in One Traversal
- Diagonal Traversal of Binary Tree
- Find Maximum Level Sum in Binary Tree using Recursion
- Clockwise Spiral Traversal of Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Iterative diagonal traversal of 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 email@example.com. 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.