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
- Print extreme nodes of each level of Binary Tree in alternate order
- 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 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 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 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
- Insertion in a Binary Tree in level order
- Sum of all nodes at Kth level in a Binary Tree
- Level Order Predecessor of a node in Binary Tree
- Level Order Successor of a node in 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.