Print Right View of a Binary Tree in Java

In this tutorial, we will learn to write a program to print the right view of a binary tree in Java.

The right view of the binary tree is all the nodes that are visible from the right side of the tree.

We can do this by traversing every level and printing the last node of each level.

For example, consider the following binary tree.

Print Right View of a Binary Tree in Java

The right view of the above tree is 1 3 5 7

Observe that all the nodes are the last nodes of each level.

ALGORITHM:

Below is the algorithm to print the right view of the binary tree.

1. Set maxLevelseen = 0.
2. Invoke function rightViewBiTree (Node = root, level = 0).
3.If the Node = null then simply return.
4.Else check if the maxLevelseen < level and print Node value and update the maxLevelseen = level.
5. Firstly make a recursive call to the function rightViewBiTree (node->right, level +1).
6. Secondly, make a recursive call to the function rightViewBiTree (node->left, level+1).

NOTE:- We call the function rightViewBiTree() first with the parameter node->right to ensure the right subtree is visited first and then with node->left to check for the left subtree.

Hence the Order of the Algorithm is:
Time complexity = O(n)
Space complexity = O(1)

Printing the right view of a binary tree in Java.

Following is the Java code to print the right view of the binary tree.

/* Class to create the node of the Binary Tree*/
class Node
{
  int data;
  Node left,right;
  public Node(int data)
  {
    this.data=data;
    left = null;
    right = null;
  }
}
/* Class to Print the Right view of Binary Tree*/
public class BiTree 
{
  static Node rootNode;
  static int maxLevelseen = 0;
  
  /*Function to print the right view of binary tree*/
  void rightViewTree(Node node, int level)
  {
    if (node==null)
    {
      return;
    }
    
    if (level > maxLevelseen)
    {
      System.out.print(node.data+" ");
      maxLevelseen = level;
    }
    
    rightViewTree(node.right, level+1); /*to visit right subtree*/
    rightViewTree(node.left, level+1); /*to visit left subtree*/
  }
  
  /*Main function*/
  public static void main(String[] args) 
  {
    BiTree bitree = new BiTree();  /*creating object*/
    
    /*creating the binary tree by inserting the nodes*/
    BiTree.rootNode = new Node(1);
    BiTree.rootNode.left = new Node(2);
    BiTree.rootNode.right = new Node(3);
    BiTree.rootNode.left.right = new Node(4);
    BiTree.rootNode.right.right = new Node(5);
    BiTree.rootNode.right.right.left = new Node(6);
    BiTree.rootNode.right.right.right = new Node(7);
    
    System.out.println("Right View of Binary Tree is ");
    
  /* Calling the function to print right view of Binary Tree*/
    bitree.rightViewbiTree(rootNode, 1);
    
  }
}

The output of the above code is:
OUTPUT:

Right view of Binary Tree is 
1 3 5 7

Leave a Reply

Your email address will not be published. Required fields are marked *