Given a binary tree, the task is to print nodes of extreme corners of each level but in alternate order.
Input : 1 / \ 2 3 / / \ 4 5 6 / / \ 7 8 9 Output : 1 2 6 7 Print the rightmost node at 1st level: 1 Print the leftmost node at 2nd level: 2 Print the rightmost node at 3rd level: 6 Print the leftmost node at 4th level: 7 Other possible output will be -> 1 3 4 9 Input : 3 / \ 8 1 / \ / \ 9 5 6 4 Output : 3 8 4
We have already discussed the iterative approach to solve this problem. In this post the recursive approach is discussed.
Approach: The idea is to perform level order traversal in the spiral form and at each level print the first node during the traversal, these will be the nodes at extreme corner present in the alternate form.
Below is the implementation of the above approach:
1 2 7 8 31
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.
- Print extreme nodes of each level of Binary Tree in alternate order
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Print the nodes corresponding to the level value for each level of a Binary Tree
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print the middle nodes of each level of a Binary Tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Connect Nodes at same Level (Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Print alternate nodes from all levels of a Binary Tree
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Difference between sums of odd level and even level nodes in an N-ary Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Level order traversal with direction change after every two levels | Recursive Approach
- Print nodes between two given level numbers of a binary tree
- Print all the nodes except the leftmost node in every level of the given 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.