VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-leftmost-and-rightmost-nodes-of-a-binary-tree/

⇱ Leftmost and Rightmost of all Levels in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

Examples:

Input:

👁 2056957843

Output: 1 2 3 4 7
Explanation:
Corners at level 0: 1
Corners at level 1: 2 3
Corners at level 2: 4 7

Input :

👁 2056957844

Output : 10 20 30 40 60
Explanation :
Corners at level 0: 10
Corners at level 1: 20 30
Corners at level 2: 40 60

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.  


Output
1 2 3 4 7 
Comment
Article Tags:
Article Tags: