Given a binary tree, the task is to print the nodes of the tree in a reverse anti-clockwise spiral manner.
Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 7 8 9 1 4 5 6 3 2 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output : 10 14 20 5 3 4 25 22 8
Approach: The idea is to use two variables i initialized to 1 and j initialized to the height of tree and run a while loop which wont break until i becomes greater than j. We will use another variable flag and initialize it to 1. Now in the while loop we will check a condition that if flag is equal to 1 we will traverse the tree from left to right and mark flag as 0 so that next time we traverse the tree from right to left and then decrement the value of j so that next time we visit the level just above the current level. Also when we will traverse the level from top we will mark flag as 1 so that next time we traverse the tree from left to right and then increment the value of i so that next time we visit the level just below the current level. Repeat the whole process until the binary tree is completely traversed.
Below is the implementation of the above approach:
10 14 20 5 3 4 25 22 8
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.
- Anti Clockwise spiral traversal of a binary tree
- Reverse Clockwise spiral traversal of a binary tree
- Element in a matrix starting from which anti-clockwise traversal ends at the last element
- Clockwise Spiral Traversal of Binary Tree
- Clockwise Spiral Traversal of Binary Tree | Set - 2
- Clockwise Triangular traversal of a Binary Tree
- Reverse Level Order traversal in spiral form
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Level order traversal of Binary Tree using Morris Traversal
- Reverse Morris traversal using Threaded Binary Tree
- Reverse zigzag Traversal of a Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Level order traversal in spiral form
- Level order traversal in spiral form | Using one stack and one queue
- Level order traversal in spiral form | Using Deque
- Level order traversal in spiral form using stack and multimap
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Maximum spiral sum in Binary Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Clockwise rotation of Linked List
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.