[Expected Approach - 1] Using Recursion – O(n) Time and O(n) Space
The idea is to use recursion and keep track of the maximum level also. And traverse the tree in a manner that the right subtree is visited before the left subtree.
Follow the steps below to solve the problem:
Perform Postorder traversal to get the rightmost node first.
Maintain a variable name maxLevel which will store till which it prints the right view.
While traversing the tree in a postorder manner if the current level is greater than maxLevel then print the current node and update maxLevel by the current level.
Below is the implementation of the above approach:
C++
// C++ program to print right view of Binary Tree// using recursion#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Helper function for the right view using RecursionvoidRecursiveRightView(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 subtreeRecursiveRightView(root->right,level+1,maxLevel,result);RecursiveRightView(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 0RecursiveRightView(root,0,maxLevel,result);returnresult;}voidprintArray(vector<int>&arr){for(intval:arr){cout<<val<<" ";}cout<<endl;}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);printArray(result);return0;}
C
// C program to print right view of Binary Tree// using recursion#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};// Helper function for the right view using RecursionvoidRecursiveRightView(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 subtreeRecursiveRightView(root->right,level+1,maxLevel,result,index);RecursiveRightView(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 0RecursiveRightView(root,0,&maxLevel,result,&index);*size=index;}voidprintArray(int*arr,intsize){for(inti=0;i<size;i++){printf("%d ",arr[i]);}printf("\n");}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);printArray(result,size);return0;}
Java
// Java program to print right view of binary tree// using Recursionimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}// Helper function for the right view using RecursionclassGfG{staticvoidRecursiveRightView(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 subtreeRecursiveRightView(root.right,level+1,maxLevel,result);RecursiveRightView(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 0RecursiveRightView(root,0,maxLevel,result);returnresult;}staticvoidprintArray(ArrayList<Integer>arr){for(intval:arr){System.out.print(val+" ");}System.out.println();}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);printArray(result);}}
Python
# Python program to print right view of Binary Tree# using RecursionclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Helper function for the right view using RecursiondefRecursiveRightView(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 subtreeRecursiveRightView(root.right,level+1,maxLevel,result)RecursiveRightView(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 0RecursiveRightView(root,0,maxLevel,result)returnresultdefprintArray(arr):forvalinarr:print(val,end=" ")print()if__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)printArray(result)
C#
// C# program to print right view of binary tree// using RecursionusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Helper function for the right view using RecursionstaticvoidRecursiveRightView(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 subtreeRecursiveRightView(root.right,level+1,refmaxLevel,result);RecursiveRightView(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 0RecursiveRightView(root,0,refmaxLevel,result);returnresult;}staticvoidPrintList(List<int>arr){foreach(intvalinarr){Console.Write(val+" ");}Console.WriteLine();}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);PrintList(result);}}
JavaScript
// JavaScript program to print right view// of binary tree using RecursionclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Helper function for the right view using RecursionfunctionrecursiveRightView(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 subtreerecursiveRightView(root.right,level+1,maxLevel,result);recursiveRightView(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 0recursiveRightView(root,0,maxLevel,result);returnresult;}// Function to print the arrayfunctionprintArray(arr){console.log(arr.join(' '));}// 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);printArray(result);
Output
1 3 5
Time Complexity: O(n), We traverse all nodes of the binary tree exactly once, where n is the number of nodes. Auxiliary Space: O(h), The space required for the recursion stack will be proportional to the height(h) of the tree, which could be as large as n for a skewed tree.
[Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space
The idea is to traverse the tree level by level and print the last node at each level (the rightmost node). A simple solution is to do level order traversal and print the last node in every level. Please refer to Right view of Binary Tree using Queue for implementation.
[Expected Approach - 3] Using Morris Traversal – O(n) Time and O(1) Space
The idea is to use Morris Traversalto print the right view of the binary tree by dynamically adjusting the tree's structure during traversal. An empty list is maintained to store the rightmost nodes encountered at each level.
Follow the steps below to implement the idea:
Create an empty list view to store the right view nodes and set a variable level to 0 to track the current level of traversal.
Use a pointer root to traverse the binary tree. While root is not null, proceed with the traversal.
If the current node has a right child, find its inorder predecessor by traversing the leftmost nodes of the right subtree.
If the left child of the predecessor is null, add the current node's value to view if it’s the first visit to that level. Then establish a thread from the predecessor to the current node and move to the right child.
If the left child of the predecessor is already pointing to the current node (indicating a second visit), remove the thread and move to the left child of the current node.
If the current node does not have a right child, add its value to res if it’s the first visit at that level, then move to its left child for further traversal.
Below is the implementation of the above approach.
C++
// C++ program to print right view of Binary// tree using modified Morris Traversal#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to return the right view of the binary treevector<int>rightView(Node*root){// To store the right view nodesvector<int>res;// Current level of traversalintlevel=0;// Traverse the tree using modified Morris Traversalwhile(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++;}}// Return the right view nodesreturnres;}voidprintArray(vector<int>&arr){for(intval:arr){cout<<val<<" ";}cout<<endl;}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);printArray(result);return0;}
Java
// Java program to print right view of Binary// tree using modified Morris Traversalimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}// Function to return the right view of the binary treeclassGfG{publicstaticArrayList<Integer>rightView(Noderoot){// To store the right view nodesArrayList<Integer>res=newArrayList<>();// Current level of traversalintlevel=0;// Traverse the tree using modified // Morris Traversalwhile(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;}staticvoidprintArray(ArrayList<Integer>arr){for(intval:arr){System.out.print(val+" ");}System.out.println();}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);printArray(result);}}
Python
# Python program to print right view of Binary Tree# using modified Morris TraversalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to return the right view of the binary treedefrightView(root):# To store the right view nodesres=[]# Current level of traversallevel=0# Traverse the tree using modified Morris Traversalwhileroot:# If the node has a right child,# find the inorder predecessorifroot.right:pred=root.rightbackDepth=1# Find the leftmost node in the right subtreewhilepred.leftandpred.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+=1# Return the right view nodesreturnresdefprintArray(arr):forvalinarr:print(val,end=" ")print()if__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)printArray(result)
C#
// C# program to print right view of Binary Tree// using modified Morris TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}// Function to return the right view of the binary treeclassGfG{staticList<int>rightView(Noderoot){// To store the right view nodesList<int>res=newList<int>();// Current level of traversalintlevel=0;// Traverse the tree using modified // Morris Traversalwhile(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++;}}// Return the right view nodesreturnres;}staticvoidprintArray(List<int>arr){foreach(intvalinarr){Console.Write(val+" ");}Console.WriteLine();}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);printArray(result);}}
JavaScript
// JavaScript program to print right view of Binary// tree using modified Morris TraversalclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to return the right view of the binary treefunctionrightView(root){// To store the right view nodesconstres=[];// Current level of traversalletlevel=0;// Traverse the tree using modified Morris Traversalwhile(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&&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++;}}// Return the right view nodesreturnres;}functionprintArray(arr){console.log(arr.join(' '));}// 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);printArray(result);
Output
1 3 5
Time Complexity:O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly twice (once when we find its inorder predecessor, and once when we visit it from its inorder predecessor). Auxiliary Space: O(1), because we only use a constant amount of extra space for the pointers. We do not use any additional data structures or recursive function calls that would increase the space complexity.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.