Right View of a Binary Tree

Given a binary tree, we have to write a code to print the right view of a binary tree.

Right View of a Binary Tree

The right view of a binary tree is the set of visible nodes when it is visited or seen from the right side.

For example:

Example 1:

Let’s take an example. In this binary tree, the node which is visible from the right side is 1, 3, 4, and 8.

print right view of a binary tree

Example 2:

In the second example, the node which is visible from the right side is 7, 5, and 1.

Print right view of a binary tree in java using queue

We have discussed the problem statement with multiple examples. Before checking the solution, think about how you can approach this problem? Which data structure do you use to solve this problem.

At the end of this post, I have shared the link to the video tutorial.

Programming video tutorials

Right View of a Binary Tree using Queue – Java Code

In this example, I have explained how to print the right view of a binary tree using level order traversal of a binary tree.

The idea here is to traverse a binary tree using level order traversal and print the last node of each level.

Here are the following steps:

i) Declare a queue and add a root node in a queue.
ii) Run a while loop while the queue is not empty and do the following steps

a) Find the length (no. of nodes present in a queue).

b) Run a loop from 0 to length-1.

c) Poll a node from the queue and check if it’s the last node of that level. If it’s then print the node value.

d) Add the left and right child of a node in a queue. If it’s not null.

iii) Repeat these steps until the binary tree is traversed completely.

The time and space complexity of this approach is O(n). This problem is similar to the print left view of a binary tree.

Binary Tree Right Side View LeetCode Solution

In this section, let’s discuss the LeetCode solution to a similar problem. The idea is the same, we do the level order traversal and pick the last node of each level.

Binary tree right side view video tutorial

In this video tutorial, I have explained how we can print the right view of a tree using a queue.

Print right view of a binary tree video tutorial

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.