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 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 odd positioned nodes of odd levels in level order of the given binary tree
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Print nodes between two given level numbers of a binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Flatten Binary Tree in order of Level Order Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Sum of all nodes at Kth level in a Binary Tree
- Insertion in a Binary Tree in level order
- Count half nodes in a Binary tree (Iterative and Recursive)
- Count full nodes in a Binary tree (Iterative and Recursive)
- Swap Nodes in Binary tree of every k'th level
- Nodes at Kth level without duplicates in a Binary Tree
- Boundary Level order traversal of a Binary Tree
- Specific Level Order 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 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.