Leftmost and Rightmost of all Levels in a Binary Tree
Last Updated : 9 May, 2026
Given the root of a binary tree, find the corner nodes from root to the last level. The corner nodes are the leftmost and rightmost nodes at each level of the binary tree.
Using Recursive Approach - O(n) Time and O(n) Space
The idea is to use recursion and track the level of each node. For every level, the first visited node is stored as the leftmost, and the last visited node is updated as the rightmost. Finally, we print both for each level (avoiding duplicates).
Output
1 2 3 4 7
Using Level Order Traversal - O(n) Time and O(n) Space
The idea is to use Level Order Traversal. Every time we store the size of the queue in a variable n, which is the number of nodes at that level. For every level, we check whether the current node is the first (i.e node at index 0) and the node at the last index (i.e node at index n-1) If it is either of them, we print the value of that node.