Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost.
Can we print all corner nodes using one traversal?
The idea is to use Level Order Traversal. To find first node, we use a variable isFirst. To separate levels, we enqueue NULL after every level. So in level order traversal, if we see a NULL, we know next node would be first node of its level and therefore we set isFirst.
A special case to consider is, a tree like below.
1 \ 2 \ 3
The output for above tree should be 1, 2, 3. We need make sure that the levels having only one node are handled and the node is printed only once. For this purpose, we maintain a separate variable isOne.
15 10 20 8 25
Time Complexity : O(n) where n is number of nodes in Binary Tree.
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print all even nodes of Binary Search Tree
- Print all nodes in a binary tree having K leaves
- Print Levels of all nodes in a Binary Tree
- Print all full nodes in a Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print all nodes between two given levels in Binary Tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print all leaf nodes of a Binary Tree from left to right
- Print extreme nodes of each level of Binary Tree in alternate order
- Sum of all nodes in a binary tree
- Print the nodes at odd levels of a tree
- Sink Odd nodes in Binary Tree