Given a binary tree, print nodes of extreme corners of each level but in alternate order.
For above tree, the output can be
1 2 7 8 31
– print rightmost node of 1st level
– print leftmost node of 2nd level
– print rightmost node of 3rd level
– print leftmost node of 4th level
– print rightmost node of 5th level
1 3 4 15 16
– print leftmost node of 1st level
– print rightmost node of 2nd level
– print leftmost node of 3rd level
– print rightmost node of 4th level
– print leftmost node of 5th level
The idea is to traverse tree level by level. For each level, we count number of nodes in it and print its leftmost or the rightmost node based on value of a Boolean flag. We dequeue all nodes of current level and enqueue all nodes of next level and invert value of Boolean flag when switching levels.
Below is the implementation of above idea –
1 2 7 8 31
Time complexity of above solution is O(n) where n is total number of nodes in given binary tree.
Exercise – Print nodes of extreme corners of each level from bottom to top in alternate order.
This article is contributed by Aditya Goel. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Recursive Program to 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 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
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Insertion in a Binary Tree in level order
- Swap Nodes in Binary tree of every k'th level
- Density of Binary Tree using Level Order Traversal
- Level Order Successor of a node in Binary Tree
- Level Order Predecessor of a node in Binary Tree
- Count nodes with two children at level L in a Binary Tree
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
Improved By : andrew1234