Given the root of a binary Tree, find the right view of the Binary Tree. The right view of a binary tree is a list of nodes you see when you look at the tree from the right side. It contains the rightmost node at each level, starting from the root (top level) down to the deepest level, in order.
Examples:
Input:
Output: [1, 3, 4, 5] Explanation: The Greencolored nodes (1, 3, 4, 5) represents the Right view in the below Binary tree.
Input:
Output: [1, 3, 5] Explanation: The Greencolored nodes (1, 3, 5) represents the Right view in the below Binary tree
The idea is to traverse the complete tree recursively. Because we need the right view, At each step, we first go to the right subtree and then to the left subtree. For each level, we store the first node we encounter (the rightmost node for that level). By traversing the entire tree this way, we ensure that every level contributes its rightmost node to the result.
C++
#include<iostream>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function for the right view using RecursionvoidrecRightView(Node*root,intlevel,int&maxLevel,vector<int>&result){if(!root)return;// If current level is more than max level,// this is the first node of that levelif(level>maxLevel){result.push_back(root->data);maxLevel=level;}// Traverse right subtree first, then left subtreerecRightView(root->right,level+1,maxLevel,result);recRightView(root->left,level+1,maxLevel,result);}// Function to return the right view of the binary treevector<int>rightView(Node*root){vector<int>result;intmaxLevel=-1;// Start recursion with root at level 0recRightView(root,0,maxLevel,result);returnresult;}intmain(){// Representation of the input tree:// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<int>result=rightView(root);for(intval:result){cout<<val<<" ";}return0;}
C
#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{intdata;structNode*left,*right;};// function for the right view using RecursionvoidrecRightView(structNode*root,intlevel,int*maxLevel,int*result,int*index){if(!root)return;// If current level is more than max level,// this is the first node of that levelif(level>*maxLevel){result[(*index)++]=root->data;*maxLevel=level;}// Traverse right subtree first, then // left subtreerecRightView(root->right,level+1,maxLevel,result,index);recRightView(root->left,level+1,maxLevel,result,index);}// Function to return the right view of the binary treevoidrightView(structNode*root,int*result,int*size){intmaxLevel=-1;intindex=0;// Start recursion with root at level 0recRightView(root,0,&maxLevel,result,&index);*size=index;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){// Representation of the input tree:// 1// / \ // 2 3// / \ // 4 5 structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->right->left=createNode(4);root->right->right=createNode(5);intresult[100];intsize=0;rightView(root,result,&size);for(inti=0;i<size;i++){printf("%d ",result[i]);}return0;}
Java
importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// function for the right view using RecursionstaticvoidrecRightView(Noderoot,intlevel,int[]maxLevel,ArrayList<Integer>result){if(root==null)return;// If current level is more than max level,// this is the first node of that levelif(level>maxLevel[0]){result.add(root.data);maxLevel[0]=level;}// Traverse right subtree first, then left subtreerecRightView(root.right,level+1,maxLevel,result);recRightView(root.left,level+1,maxLevel,result);}// Function to return the right view of the binary treestaticArrayList<Integer>rightView(Noderoot){ArrayList<Integer>result=newArrayList<>();int[]maxLevel=newint[]{-1};// Start recursion with root at level 0recRightView(root,0,maxLevel,result);returnresult;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);ArrayList<Integer>result=rightView(root);for(intval:result){System.out.print(val+" ");}}}
Python
# Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# function for the right view using RecursiondefrecRightView(root,level,maxLevel,result):ifrootisNone:return# If current level is more than max level,# this is the first node of that leveliflevel>maxLevel[0]:result.append(root.data)maxLevel[0]=level# Traverse right subtree first, then left subtreerecRightView(root.right,level+1,maxLevel,result)recRightView(root.left,level+1,maxLevel,result)# Function to return the right view of the binary treedefrightView(root):result=[]maxLevel=[-1]# Start recursion with root at level 0recRightView(root,0,maxLevel,result)returnresultif__name__=="__main__":# Representation of the input tree:# 1# / \# 2 3# / \ # 4 5 root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=rightView(root)forvalinresult:print(val,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// function for the right view using RecursionstaticvoidrecRightView(Noderoot,intlevel,refintmaxLevel,List<int>result){if(root==null)return;// If current level is more than max level,// this is the first node of that levelif(level>maxLevel){result.Add(root.data);maxLevel=level;}// Traverse right subtree first, then left subtreerecRightView(root.right,level+1,refmaxLevel,result);recRightView(root.left,level+1,refmaxLevel,result);}// Function to return the right view of the binary treestaticList<int>rightView(Noderoot){List<int>result=newList<int>();intmaxLevel=-1;// Start recursion with root at level 0recRightView(root,0,refmaxLevel,result);returnresult;}staticvoidMain(string[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<int>result=rightView(root);foreach(intvalinresult){Console.Write(val+" ");}Console.WriteLine();}}
JavaScript
// Node StructureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// function for the right view using RecursionfunctionrecRightView(root,level,maxLevel,result){if(root===null)return;// If current level is more than max level,// this is the first node of that levelif(level>maxLevel[0]){result.push(root.data);maxLevel[0]=level;}// Traverse right subtree first, then left subtreerecRightView(root.right,level+1,maxLevel,result);recRightView(root.left,level+1,maxLevel,result);}// Function to return the right view of the binary treefunctionrightView(root){letresult=[];letmaxLevel=[-1];// Start recursion with root at level 0recRightView(root,0,maxLevel,result);returnresult;}// Driver Code// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);letresult=rightView(root);console.log(result.join(' '));
Output
1 3 5
Time Complexity: O(n), We traverse all nodes of the binary tree exactly once. Auxiliary Space: O(h), The space required for the recursion stack will be proportional to the height(h) of the tree.
[Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space
The idea is to use level-order traversal to solve this problem. By traversing the tree level by level, we can store the last node of each level, which represents the rightmost node, to form the right view.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};vector<int>rightView(Node*root){vector<int>result;if(root==nullptr)returnresult;// Queue for level order traversalqueue<Node*>q;q.push(root);while(!q.empty()){// Number of nodes at current levelintlevelSize=q.size();for(inti=0;i<levelSize;i++){Node*curr=q.front();q.pop();// If it's the last node of the current levelif(i==levelSize-1){result.push_back(curr->data);}// Enqueue left childif(curr->left!=nullptr){q.push(curr->left);}// Enqueue right childif(curr->right!=nullptr){q.push(curr->right);}}}returnresult;}intmain(){// Representation of the input tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<int>result=rightView(root);for(intval:result){cout<<val<<" ";}cout<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{staticArrayList<Integer>rightView(Noderoot){ArrayList<Integer>result=newArrayList<>();if(root==null){returnresult;}// Queue for level order traversalQueue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){// Number of nodes at the current levelintlevelSize=q.size();for(inti=0;i<levelSize;i++){Nodecurr=q.poll();// If it's the last node of the current// levelif(i==levelSize-1){result.add(curr.data);}// Enqueue left childif(curr.left!=null){q.add(curr.left);}// Enqueue right childif(curr.right!=null){q.add(curr.right);}}}returnresult;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);ArrayList<Integer>result=rightView(root);for(intval:result){System.out.print(val+" ");}System.out.println();}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to return the right view of the binary treedefrightView(root):result=[]ifrootisNone:returnresult# Queue for level order traversalq=deque([root])whileq:# Number of nodes at the current levellevel_size=len(q)foriinrange(level_size):curr=q.popleft()# If it's the last node of the# current levelifi==level_size-1:result.append(curr.data)# Enqueue left childifcurr.leftisnotNone:q.append(curr.left)# Enqueue right childifcurr.rightisnotNone:q.append(curr.right)returnresultif__name__=="__main__":# Representation of the input tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=rightView(root)forvalinresult:print(val,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{staticList<int>rightView(Noderoot){List<int>result=newList<int>();if(root==null){returnresult;}// Queue for level order traversalQueue<Node>queue=newQueue<Node>();queue.Enqueue(root);while(queue.Count>0){// Number of nodes at the current levelintlevelSize=queue.Count;for(inti=0;i<levelSize;i++){Nodecurr=queue.Dequeue();// If it's the last node of// the current levelif(i==levelSize-1){result.Add(curr.data);}// Enqueue left childif(curr.left!=null){queue.Enqueue(curr.left);}// Enqueue right childif(curr.right!=null){queue.Enqueue(curr.right);}}}returnresult;}staticvoidMain(string[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<int>result=rightView(root);foreach(intvalinresult){Console.Write(val+" ");}}}
JavaScript
// Node StructureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Custom Queue ClassclassQueue{constructor(){this.items=[];this.frontIndex=0;this.backIndex=0;}enqueue(item){this.items[this.backIndex++]=item;}dequeue(){if(this.isEmpty())returnnull;constitem=this.items[this.frontIndex];deletethis.items[this.frontIndex++];returnitem;}getlength(){returnthis.backIndex-this.frontIndex;}isEmpty(){returnthis.length===0;}}functionrightView(root){letresult=[];if(root===null){returnresult;}// Queue for level order traversalletqueue=newQueue();queue.enqueue(root);while(queue.length>0){// Number of nodes at the current levelletlevelSize=queue.length;for(leti=0;i<levelSize;i++){letcurr=queue.dequeue();// If it's the last node of the // current levelif(i===levelSize-1){result.push(curr.data);}// Enqueue left childif(curr.left!==null){queue.enqueue(curr.left);}// Enqueue right childif(curr.right!==null){queue.enqueue(curr.right);}}}returnresult;}// Driver Code// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);letresult=rightView(root);console.log(result.join(' '));
Output
1 3 5
[Expected Approach - 3] Using Morris Traversal – O(n) Time and O(1) Space
The idea is to use Morris Traversal to print the right view of the binary tree by dynamically adjusting the tree's structure during traversal.
Follow the steps below to implement the idea:
Start with the root and keep moving while nodes exist.
If the current node has a right child, find its inorder predecessor (leftmost node of right subtree).
If visiting the predecessor for the first time: -> Record the current node’s value for the right view. -> Make a temporary thread from the predecessor back to the current node. -> Move to the right child.
If the predecessor already points back to the current node: -> Remove the thread. -> Move to the left child.
If the current node has no right child: -> Record its value if it’s the first node at this level. -> Move to the left child.
Repeat until all nodes are visited. The recorded values form the right view.
C++
#include<iostream>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};vector<int>rightView(Node*root){vector<int>res;intlevel=0;while(root){// If the node has a right child,// find the inorder predecessorif(root->right){Node*pred=root->right;intbackDepth=1;// Find the leftmost node in the right subtreewhile(pred->left!=nullptr&&pred->left!=root){pred=pred->left;backDepth++;}// If threading is not yet establishedif(pred->left==nullptr){// Add the current node to the view if // visiting the level for the first timeif(res.size()==level){res.push_back(root->data);}// Establish the thread and move // to the right subtreepred->left=root;root=root->right;level++;}else{// Threading was already done//(second visit) remove the thread and // go to the left subtreepred->left=nullptr;root=root->left;level-=backDepth;}}else{// If no right child, process the current // node and move to the left childif(res.size()==level){res.push_back(root->data);}root=root->left;level++;}}returnres;}intmain(){// Representation of the input tree:// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);vector<int>result=rightView(root);for(intval:result){cout<<val<<" ";}cout<<endl;return0;}
Java
importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{staticArrayList<Integer>rightView(Noderoot){ArrayList<Integer>res=newArrayList<>();intlevel=0;while(root!=null){// If the node has a right child,// find the inorder predecessorif(root.right!=null){Nodepred=root.right;intbackDepth=1;// Find the leftmost node in the right subtreewhile(pred.left!=null&&pred.left!=root){pred=pred.left;backDepth++;}// If threading is not yet establishedif(pred.left==null){// Add the current node to the view if // visiting the level for the first timeif(res.size()==level){res.add(root.data);}// Establish the thread and move // to the right subtreepred.left=root;root=root.right;level++;}else{// Threading was already done//(second visit) remove the thread and // go to the left subtreepred.left=null;root=root.left;level-=backDepth;}}else{// If no right child, process the current // node and move to the left childif(res.size()==level){res.add(root.data);}root=root.left;level++;}}returnres;}publicstaticvoidmain(String[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);ArrayList<Integer>result=rightView(root);for(intval:result){System.out.print(val+" ");}System.out.println();}}
Python
# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefrightView(root):res=[]level=0whileroot:# If the node has a right child,# find the inorder predecessorifroot.right:pred=root.rightbackDepth=1# Find the leftmost node in the right subtreewhilepred.leftisnotNoneandpred.left!=root:pred=pred.leftbackDepth+=1# If threading is not yet establishedifpred.leftisNone:# Add the current node to the view if# visiting the level for the first timeiflen(res)==level:res.append(root.data)# Establish the thread and move# to the right subtreepred.left=rootroot=root.rightlevel+=1else:# Threading was already done# (second visit) remove the thread and# go to the left subtreepred.left=Noneroot=root.leftlevel-=backDepthelse:# If no right child, process the current# node and move to the left childiflen(res)==level:res.append(root.data)root=root.leftlevel+=1returnresif__name__=="__main__":# Representation of the input tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)result=rightView(root)print(" ".join(map(str,result)))
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{staticList<int>rightView(Noderoot){List<int>res=newList<int>();intlevel=0;while(root!=null){// If the node has a right child,// find the inorder predecessorif(root.right!=null){Nodepred=root.right;intbackDepth=1;// Find the leftmost node in the right subtreewhile(pred.left!=null&&pred.left!=root){pred=pred.left;backDepth++;}// If threading is not yet establishedif(pred.left==null){// Add the current node to the view if // visiting the level for the first timeif(res.Count==level){res.Add(root.data);}// Establish the thread and move // to the right subtreepred.left=root;root=root.right;level++;}else{// Threading was already done//(second visit) remove the thread and // go to the left subtreepred.left=null;root=root.left;level-=backDepth;}}else{// If no right child, process the current // node and move to the left childif(res.Count==level){res.Add(root.data);}root=root.left;level++;}}returnres;}staticvoidMain(string[]args){// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);List<int>result=rightView(root);foreach(intvalinresult){Console.Write(val+" ");}Console.WriteLine();}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionrightView(root){constres=[];letlevel=0;while(root){// If the node has a right child,// find the inorder predecessorif(root.right){letpred=root.right;letbackDepth=1;// Find the leftmost node in the right subtreewhile(pred.left!==null&&pred.left!==root){pred=pred.left;backDepth++;}// If threading is not yet establishedif(pred.left===null){// Add the current node to the view if // visiting the level for the first timeif(res.length===level){res.push(root.data);}// Establish the thread and move // to the right subtreepred.left=root;root=root.right;level++;}else{// Threading was already done//(second visit) remove the thread and // go to the left subtreepred.left=null;root=root.left;level-=backDepth;}}else{// If no right child, process the current // node and move to the left childif(res.length===level){res.push(root.data);}root=root.left;level++;}}returnres;}// Driver code// Representation of the input tree:// 1// / \// 2 3// / \ // 4 5 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);constresult=rightView(root);console.log(result.join(' '));