Given a binary tree, write an efficient algorithm to print its right view.

For example, the right view of the following binary tree is 1, 3, 6, 8:

 
Print right view of a binary tree

Practice this problem

1. Iterative Implementation using Queue

In an iterative version, perform a level order traversal on the tree. The idea is to modify level order traversal to maintain nodes at the current level. Then if the current node is the last node of the current level, print it.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 3 6 8

Java


Download  Run Code

Output:

1 3 6 8

Python


Download  Run Code

Output:

1 3 6 8

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.

2. Recursive Implementation using Hashing

We can also solve this problem by using hashing. The idea is to traverse the tree in a preorder fashion and pass level information in function arguments. For every node encountered, insert the node and level information into the map. Finally, when all nodes are processed, traverse the map and print the right view.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

1 3 6 8

Java


Download  Run Code

Output:

1 3 6 8

Python


Download  Run Code

Output:

[1, 3, 6, 8]

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.

3. Recursive Implementation (using Preorder Traversal)

We can also solve this problem by using constant space and linear time. The idea is to traverse the tree in reverse preorder fashion (visit the right subtree before the left subtree) and maintain the maximum level visited so far. If the current level is more than the maximum level visited so far, then the current node is the last node of the current level, and we print it and update the last level to the current level.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

1 3 6 8

Java


Download  Run Code

Output:

1 3 6 8

Python


Download  Run Code

Output:

1 3 6 8

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.

 
Exercise: Print left view of a binary tree