Print Right View of a Binary Tree
Last Updated :
24 Aug, 2023
Given a Binary Tree, print the Right view of it.
The right view of a Binary Tree is a set of nodes visible when the tree is visited from the Right side.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Output: Right view of the tree is 1 3 7 8
Input:
1
/
8
/
7
Output: Right view of the tree is 1 8 7
Right View of a Binary Tree using Recursion:
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 max_level 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 max_level then print the current node and update max_level by the current level
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int item)
{
struct Node* temp
= ( struct Node*) malloc ( sizeof ( struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void rightViewUtil( struct Node* root, int level,
int * max_level)
{
if (root == NULL)
return ;
if (*max_level < level) {
cout << root->data << "\t" ;
*max_level = level;
}
rightViewUtil(root->right, level + 1, max_level);
rightViewUtil(root->left, level + 1, max_level);
}
void rightView( struct Node* root)
{
int max_level = 0;
rightViewUtil(root, 1, &max_level);
}
int main()
{
struct Node* 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);
root->right->right->right = newNode(8);
rightView(root);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int item)
{
struct Node* temp
= ( struct Node*) malloc ( sizeof ( struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void rightViewUtil( struct Node* root, int level,
int * max_level)
{
if (root == NULL)
return ;
if (*max_level < level) {
printf ( "%d\t" , root->data);
*max_level = level;
}
rightViewUtil(root->right, level + 1, max_level);
rightViewUtil(root->left, level + 1, max_level);
}
void rightView( struct Node* root)
{
int max_level = 0;
rightViewUtil(root, 1, &max_level);
}
int main()
{
struct Node* 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);
root->right->left->right = newNode(8);
rightView(root);
return 0;
}
|
Java
class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class Max_level {
int max_level;
}
class BinaryTree {
Node root;
Max_level max = new Max_level();
void rightViewUtil(Node node, int level,
Max_level max_level)
{
if (node == null )
return ;
if (max_level.max_level < level) {
System.out.print(node.data + " " );
max_level.max_level = level;
}
rightViewUtil(node.right, level + 1 , max_level);
rightViewUtil(node.left, level + 1 , max_level);
}
void rightView() { rightView(root); }
void rightView(Node node)
{
rightViewUtil(node, 1 , max);
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 7 );
tree.root.right.left.right = new Node( 8 );
tree.rightView();
}
}
|
Python
class Node:
def __init__( self , item):
self .data = item
self .left = None
self .right = None
def rightViewUtil(root, level, max_level):
if root is None :
return
if (max_level[ 0 ] < level):
print "%d " % (root.data),
max_level[ 0 ] = level
rightViewUtil(root.right, level + 1 , max_level)
rightViewUtil(root.left, level + 1 , max_level)
def rightView(root):
max_level = [ 0 ]
rightViewUtil(root, 1 , max_level)
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 )
root.right.left.right = Node( 8 )
rightView(root)
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class Max_level {
public int max_level;
}
public class BinaryTree {
public Node root;
public Max_level max = new Max_level();
public virtual void rightViewUtil(Node node, int level,
Max_level max_level)
{
if (node == null ) {
return ;
}
if (max_level.max_level < level) {
Console.Write(node.data + " " );
max_level.max_level = level;
}
rightViewUtil(node.right, level + 1, max_level);
rightViewUtil(node.left, level + 1, max_level);
}
public virtual void rightView() { rightView(root); }
public virtual void rightView(Node node)
{
rightViewUtil(node, 1, max);
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
tree.rightView();
}
}
|
Javascript
<script>
class Node
{
constructor(item) {
this .left = null ;
this .right = null ;
this .data = item;
}
}
let max_level = 0;
let root;
function rightViewUtil(node, level) {
if (node == null )
return ;
if (max_level < level) {
document.write(node.data + " " );
max_level = level;
}
rightViewUtil(node.right, level + 1);
rightViewUtil(node.left, level + 1);
}
function rightView()
{
rightview(root);
}
function rightview(node) {
rightViewUtil(node, 1);
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
rightView();
</script>
|
Right view of Binary Tree using Queue
Time Complexity: O(N), Traversing the Tree having N nodes
Auxiliary Space: O(N), Function Call stack space in the worst case.
The idea is to use Level Order Traversal as the last node every level gives the right view of the binary tree.
Follow the steps below to solve the problem:
- Perform level order traversal on the tree
- At every level print the last node of that level
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void printRightView(Node* root)
{
if (root == NULL)
return ;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
while (n--) {
Node* x = q.front();
q.pop();
if (n == 0) {
cout << x->data << " " ;
}
if (x->left)
q.push(x->left);
if (x->right)
q.push(x->right);
}
}
}
int main()
{
Node* 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);
root->right->left->right = newNode(8);
printRightView(root);
}
|
Java
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
class BinaryTree {
Node root;
void rightView(Node root)
{
if (root == null ) {
return ;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
for ( int i = 0 ; i < n; i++) {
Node curr = q.peek();
q.remove();
if (i == n - 1 ) {
System.out.print(curr.data);
System.out.print( " " );
}
if (curr.left != null ) {
q.add(curr.left);
}
if (curr.right != null ) {
q.add(curr.right);
}
}
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 7 );
tree.root.right.left.right = new Node( 8 );
tree.rightView(tree.root);
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , val):
self .data = val
self .left = None
self .right = None
def rightView(root):
if root is None :
return
q = deque()
q.append(root)
while q:
n = len (q)
while n > 0 :
n - = 1
node = q.popleft()
if n = = 0 :
print (node.data, end = " " )
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
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 )
root.right.left.right = Node( 8 )
rightView(root)
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
public class BinaryTree {
public Node root;
public void rightView(Node root)
{
if (root == null ) {
return ;
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count != 0) {
int n = q.Count;
for ( int i = 0; i < n; i++) {
Node curr = q.Peek();
q.Dequeue();
if (i == n - 1) {
Console.Write(curr.data);
Console.Write( " " );
}
if (curr.left != null ) {
q.Enqueue(curr.left);
}
if (curr.right != null ) {
q.Enqueue(curr.right);
}
}
}
}
public static void Main()
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
tree.rightView(tree.root);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function newNode(data)
{
let temp = new Node(data);
return temp;
}
function printRightView(root)
{
if (root == null )
return ;
let q = [];
q.push(root);
while (q.length > 0) {
let n = q.length;
while (n-- > 0) {
let x = q[0];
q.shift();
if (n == 0) {
document.write(x.data + " " );
}
if (x.left != null )
q.push(x.left);
if (x.right != null )
q.push(x.right);
}
}
}
let 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);
root.right.left.right = newNode(8);
printRightView(root);
</script>
|
Time Complexity: O(N), where N is the number of nodes in the binary tree.
Auxiliary Space: O(N) since using auxiliary space for queue
Right View of a Binary Tree using Morris Traversal:
Follow the Steps to implement the approach:
- Initialize an empty vector res to hold the result.
- Initialize a pointer curr to the root of the binary tree.
- While curr is not null, do the following:
If curr has no right child:
Add the value of curr to res.
Set curr to its right child.
Otherwise:
Find the inorder successor of curr by initializing a pointer next to the right child of curr, and then repeatedly moving left until next has no left child or its left child is equal to curr.
If next has no left child:
Add the value of curr to res.
Set the left child of next to curr.
Set curr to its right child.
Otherwise:
Set the left child of next to null.
Set curr to its left child.
- Return res, which contains the last node at each level of the binary tree as seen from the right side.
Below is the implementation of the above approach.
C++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode( int x)
: val(x)
, left(NULL)
, right(NULL)
{
}
};
vector< int > rightSideView(TreeNode* root)
{
vector< int > res;
TreeNode* curr = root;
while (curr) {
if (!curr->right) {
res.push_back(curr->val);
curr = curr->right;
}
else {
TreeNode* next
= curr->right;
while (next->left
&& next->left
!= curr) {
next = next->left;
}
if (!next->left) {
res.push_back(curr->val);
next->left = curr;
curr = curr->right;
}
else {
next->left = NULL;
curr = curr->left;
}
}
}
return res;
}
int main()
{
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
root->right->right->right = new TreeNode(8);
vector< int > res = rightSideView(root);
for ( int i : res) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode( int val)
{
this .val = val;
this .left = null ;
this .right = null ;
}
}
public class RightSideView {
public List<Integer> rightSideView(TreeNode root)
{
List<Integer> res = new ArrayList<>();
TreeNode curr = root;
int n = 4 ;
while (curr != null ) {
if (curr.right
== null ) {
res.add(curr.val);
curr = curr.left;
}
else {
TreeNode next
= curr.right;
while (
next.left != null
&& next.left
!= curr) {
next = next.left;
}
if (next.left
== null ) {
res.add(curr.val);
next.left = curr;
curr = curr.right;
}
else {
next.left = null ;
curr = curr.left;
}
}
}
return res.subList( 0 , Math.min(n, res.size()));
}
public static void main(String[] args)
{
TreeNode root = new TreeNode( 1 );
root.left = new TreeNode( 2 );
root.right = new TreeNode( 3 );
root.left.left = new TreeNode( 4 );
root.left.right = new TreeNode( 5 );
root.right.left = new TreeNode( 6 );
root.right.right = new TreeNode( 7 );
root.right.right.right = new TreeNode( 8 );
RightSideView rightSideView = new RightSideView();
List<Integer> res
= rightSideView.rightSideView(root);
System.out.println(res);
}
}
|
Python3
class TreeNode:
def __init__( self , x):
self .val = x
self .left = None
self .right = None
def rightSideView(root):
res = []
curr = root
while curr:
if not curr.right:
res.append(curr.val)
curr = curr.right
else :
next = curr.right
while next .left and next .left ! = curr:
next = next .left
if not next .left:
res.append(curr.val)
next .left = curr
curr = curr.right
else :
next .left = None
curr = curr.left
return res
if __name__ = = '__main__' :
root = TreeNode( 1 )
root.left = TreeNode( 2 )
root.right = TreeNode( 3 )
root.left.left = TreeNode( 4 )
root.left.right = TreeNode( 5 )
root.right.left = TreeNode( 6 )
root.right.right = TreeNode( 7 )
root.right.right.right = TreeNode( 8 )
res = rightSideView(root)
for i in res:
print (i, end = " " )
print ()
|
C#
using System;
using System.Collections.Generic;
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode( int x)
{
val = x;
left = null ;
right = null ;
}
}
public class RightSideView
{
public List< int > MorrisTraversal(TreeNode root)
{
List< int > res = new List< int >();
TreeNode curr = root;
while (curr != null )
{
if (curr.right == null )
{
res.Add(curr.val);
curr = curr.right;
}
else
{
TreeNode next = curr.right;
while (next.left != null && next.left != curr)
{
next = next.left;
}
if (next.left == null )
{
res.Add(curr.val);
next.left = curr;
curr = curr.right;
}
else
{
next.left = null ;
curr = curr.left;
}
}
}
return res;
}
public static void Main( string [] args)
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
root.right.right.right = new TreeNode(8);
RightSideView rightSideView = new RightSideView();
List< int > res = rightSideView.MorrisTraversal(root);
foreach ( int val in res)
{
Console.Write(val + " " );
}
Console.WriteLine();
}
}
|
Javascript
class TreeNode {
constructor(val) {
this .val = val;
this .left = null ;
this .right = null ;
}
}
function rightSideView(root) {
const res = [];
let curr = root;
let n = 4;
while (curr) {
if (!curr.right) {
res.push(curr.val);
curr = curr.left;
}
else {
let next = curr.right;
while (next.left && next.left !== curr) {
next = next.left;
}
if (!next.left) {
res.push(curr.val);
next.left = curr;
curr = curr.right;
}
else {
next.left = null ;
curr = curr.left;
}
}
}
return res.slice(0, n);
}
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
root.right.right.right = new TreeNode(8);
const res = rightSideView(root);
console.log(res);
|
Time Complexity: O(n) , The time complexity of the Morris Traversal approach is 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) , The space complexity of the Morris Traversal approach is O(1), because we only use a constant amount of extra space for the res, curr, and next pointers. We do not use any additional data structures or recursive function calls that would increase the space complexity.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...