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:
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 :
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).
C++
#include<iostream>#include<vector>usingnamespacestd;// Structure of a Binary Tree NodeclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to perform DFS traversal and store nodes level-wisevoiddfs(Node*root,intlevel,vector<vector<Node*>>&levels){// Base caseif(root==nullptr)return;// If visiting this level for the first timeif(level==levels.size()){levels.push_back({});}// Store current node at its levellevels[level].push_back(root);// Recur for left and right subtreedfs(root->left,level+1,levels);dfs(root->right,level+1,levels);}// Function to return corner nodes of binary treevector<int>getCorner(Node*root){vector<int>ans;// Edge case: empty treeif(root==nullptr)returnans;// Vector to store nodes level-wisevector<vector<Node*>>levels;// Fill levels using DFSdfs(root,0,levels);// Traverse each levelfor(auto&level:levels){// Add leftmost nodeans.push_back(level.front()->data);// Add rightmost node if differentif(level.front()!=level.back()){ans.push_back(level.back()->data);}}returnans;}// Driver codeintmain(){// Constructing the tree:// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);// Get corner nodesvector<int>result=getCorner(root);// Print resultfor(intx:result)cout<<x<<" ";return0;}
Java
importjava.util.*;// Structure of a Binary Tree NodeclassNode{publicintdata;publicNodeleft;publicNoderight;Node(intval){data=val;left=null;right=null;}}classGfG{// Function to perform DFS traversal and store nodes level-wisepublicstaticvoiddfs(Noderoot,intlevel,ArrayList<ArrayList<Node>>levels){// Base caseif(root==null)return;// If visiting this level for the first timeif(level==levels.size()){levels.add(newArrayList<>());}// Store current node at its levellevels.get(level).add(root);// Recur for left and right subtreedfs(root.left,level+1,levels);dfs(root.right,level+1,levels);}// Function to return corner nodes of binary treepublicstaticArrayList<Integer>getCorner(Noderoot){ArrayList<Integer>ans=newArrayList<>();// Edge case: empty treeif(root==null)returnans;// Vector to store nodes level-wiseArrayList<ArrayList<Node>>levels=newArrayList<>();// Fill levels using DFSdfs(root,0,levels);// Traverse each levelfor(ArrayList<Node>level:levels){// Add leftmost nodeans.add(level.get(0).data);// Add rightmost node if differentif(level.get(0)!=level.get(level.size()-1)){ans.add(level.get(level.size()-1).data);}}returnans;}publicstaticvoidmain(String[]args){// Constructing the tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);// Get corner nodesArrayList<Integer>result=getCorner(root);// Print resultfor(intx:result)System.out.print(x+" ");}}
Python
# Structure of a Binary Tree NodeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to perform DFS traversal and store nodes level-wisedefdfs(root,level,levels):# Base caseifrootisNone:return# If visiting this level for the first timeiflevel==len(levels):levels.append([])# Store current node at its levellevels[level].append(root)# Recur for left and right subtreedfs(root.left,level+1,levels)dfs(root.right,level+1,levels)# Function to return corner nodes of binary treedefgetCorner(root):ans=[]# Edge case: empty treeifrootisNone:returnans# List to store nodes level-wiselevels=[]# Fill levels using DFSdfs(root,0,levels)# Traverse each levelforlevelinlevels:# Add leftmost nodeans.append(level[0].data)# Add rightmost node if differentiflevel[0]!=level[-1]:ans.append(level[-1].data)returnans# Driver codeif__name__=="__main__":# Constructing the tree:# 1# / \# 2 3# / \ / \\# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)# Get corner nodesresult=getCorner(root)# Print resultforxinresult:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a Binary Tree NodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{// Function to perform DFS traversal and store nodes level-wisepublicvoiddfs(Noderoot,intlevel,List<List<Node>>levels){// Base caseif(root==null)return;// If visiting this level for the first timeif(level==levels.Count){levels.Add(newList<Node>());}// Store current node at its levellevels[level].Add(root);// Recur for left and right subtreedfs(root.left,level+1,levels);dfs(root.right,level+1,levels);}// Function to return corner nodes of binary treepublicList<int>getCorner(Noderoot){List<int>ans=newList<int>();// Edge case: empty treeif(root==null)returnans;// Vector to store nodes level-wiseList<List<Node>>levels=newList<List<Node>>();// Fill levels using DFSdfs(root,0,levels);// Traverse each levelforeach(varlevelinlevels){// Add leftmost nodeans.Add(level[0].data);// Add rightmost node if differentif(level[0]!=level[level.Count-1]){ans.Add(level[level.Count-1].data);}}returnans;}publicstaticvoidMain(){// Constructing the tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);// Create objectGfGobj=newGfG();// Get corner nodesList<int>result=obj.getCorner(root);// Print resultforeach(intxinresult)Console.Write(x+" ");}}
JavaScript
// Structure of a Binary Tree NodeclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to perform DFS traversal and store nodes// level-wisefunctiondfs(root,level,levels){// Base caseif(root===null)return;// If visiting this level for the first timeif(level===levels.length){levels.push([]);}// Store current node at its levellevels[level].push(root);// Recur for left and right subtreedfs(root.left,level+1,levels);dfs(root.right,level+1,levels);}// Function to return corner nodes of binary treefunctiongetCorner(root){letans=[];// Edge case: empty treeif(root===null)returnans;// Vector to store nodes level-wiseletlevels=[];// Fill levels using DFSdfs(root,0,levels);// Traverse each levelfor(letleveloflevels){// Add leftmost nodeans.push(level[0].data);// Add rightmost node if differentif(level[0]!==level[level.length-1]){ans.push(level[level.length-1].data);}}returnans;}// Constructing the tree:// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);letresult=getCorner(root);console.log(result.join(" "));
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. Â
C++
#include<iostream>#include<vector>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// A binary tree node has key, pointer to left// child and a pointer to right childvector<int>getCorner(Node*root){vector<int>result;// Queue for level order traversalqueue<Node*>q;// Push root nodeq.push(root);// Level order traversalwhile(!q.empty()){// Number of nodes at current levelintn=q.size();for(inti=0;i<n;i++){// Get front nodeNode*temp=q.front();q.pop();// If leftmost or rightmost node of levelif(i==0||i==n-1)result.push_back(temp->data);// Push childrenif(temp->left!=nullptr)q.push(temp->left);if(temp->right!=nullptr)q.push(temp->right);}}returnresult;}// Driver Codeintmain(){// Constructing the tree:// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);vector<int>ans=getCorner(root);for(intx:ans)cout<<x<<" ";return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.ArrayList;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}publicclassGFG{// A binary tree node has key, pointer to left child and a pointer to right childpublicstaticArrayList<Integer>getCorner(Noderoot){ArrayList<Integer>result=newArrayList<>();// Queue for level order traversalQueue<Node>q=newLinkedList<>();// Push root nodeq.add(root);// Level order traversalwhile(!q.isEmpty()){// Number of nodes at current levelintn=q.size();for(inti=0;i<n;i++){// Get front nodeNodetemp=q.poll();// If leftmost or rightmost node of levelif(i==0||i==n-1)result.add(temp.data);// Push childrenif(temp.left!=null)q.add(temp.left);if(temp.right!=null)q.add(temp.right);}}returnresult;}// Driver Codepublicstaticvoidmain(String[]args){// Constructing the tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);ArrayList<Integer>ans=getCorner(root);for(intx:ans)System.out.print(x+" ");}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefgetCorner(root):result=[]# queue for level order traversalq=deque()# pushing root nodeq.append(root)# Do level order traversal of Binary Treewhileq:# n is the number of nodes in current leveln=len(q)foriinrange(n):# dequeue the front node from the queuetemp=q.popleft()# If it is leftmost or rightmost node of levelifi==0ori==n-1:result.append(temp.data)# push childreniftemp.leftisnotNone:q.append(temp.left)iftemp.rightisnotNone:q.append(temp.right)returnresult# Driver codeif__name__=='__main__':root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)ans=getCorner(root)forxinans:print(x,end=' ')
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}publicclassGfG{publicList<int>getCorner(Noderoot){List<int>result=newList<int>();// Edge caseif(root==null)returnresult;// Queue for level order traversalQueue<Node>q=newQueue<Node>();// pushing root nodeq.Enqueue(root);// Do level order traversal of Binary Treewhile(q.Count>0){// n is the no of nodes in current Levelintn=q.Count;for(inti=0;i<n;i++){// dequeue the front node from the queueNodetemp=q.Dequeue();// If it is leftmost or rightmost cornerif(i==0||i==n-1)result.Add(temp.data);// push childrenif(temp.left!=null)q.Enqueue(temp.left);if(temp.right!=null)q.Enqueue(temp.right);}}returnresult;}// Driver CodepublicstaticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);GfGobj=newGfG();List<int>ans=obj.getCorner(root);foreach(intxinans)Console.Write(x+" ");}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// A binary tree node has key, pointer to left// child and a pointer to right childfunctiongetCorner(root){constresult=[];// Queue for level order traversalconstq=[];// Push root nodeq.push(root);// Level order traversalwhile(q.length>0){// Number of nodes at current levelconstn=q.length;for(leti=0;i<n;i++){// Get front nodeconsttemp=q.shift();// If leftmost or rightmost node of levelif(i===0||i===n-1)result.push(temp.data);// Push childrenif(temp.left!==null)q.push(temp.left);if(temp.right!==null)q.push(temp.right);}}returnresult;}// Driver Code{// Constructing the tree:// 1// / \// 2 3// / \ / \// 4 5 6 7constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);constans=getCorner(root);for(constxofans)console.log(x);}