Given a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.
Examples:
Example 1: TheGreen colored nodes (1, 3, 5) represents the Right view in the below Binary tree.
Example 2: TheGreen colored nodes (1, 3, 4, 5) represents the Right view in the below Binary tree.
Approach:
The idea is to traverse the treelevel by leveland 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.
Follow the steps below to implement the idea:
Perform a level order traversal of the binary tree.
For each level, print the last node in it's level order traversal.
Move to the next level and repeat until all levels are processed.
Below is the implementation of above approach:
C++
// C++ program to print right view of Binary// tree using Level order 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){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;}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 Level order Traversalimportjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to return the right view of the binary treestaticArrayList<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;}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 Level Order TraversalfromcollectionsimportdequeclassNode: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)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 Level Order TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to return the right view of // the binary treestaticList<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;}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 Level order TraversalclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to return the right view of the binary treefunctionrightView(root){letresult=[];if(root===null){returnresult;}// Queue for level order traversalletqueue=[root];while(queue.length>0){// Number of nodes at the current levelletlevelSize=queue.length;for(leti=0;i<levelSize;i++){letcurr=queue.shift();// If it's the last node of the // current levelif(i===levelSize-1){result.push(curr.data);}// Enqueue left childif(curr.left!==null){queue.push(curr.left);}// Enqueue right childif(curr.right!==null){queue.push(curr.right);}}}returnresult;}functionprintArray(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(n) since using auxiliary space for queue.