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

For example, the left view of the following binary tree is 1, 2, 4, 7:
 

Print left view of a binary tree

Practice this problem

1. Iterative Implementation

In the iterative version, perform a level order traversal on the tree. We can modify level order traversal to maintain nodes at the current level. Then if the current node is the first node of the current level, print it.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

1 2 4 7

Java


Download  Run Code

Output:

1 2 4 7

Python


Download  Run Code

Output:

1 2 4 7

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. If the level is visited for the first time, insert the current node and level information into the map. Finally, when all nodes are processed, traverse the map and print the left view.

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

C++


Download  Run Code

Output:

1 2 4 7

Java


Download  Run Code

Output:

1 2 4 7

Python


Download  Run Code

Output:

1 2 4 7

We can also traverse nodes in reverse preorder fashion, as shown below:

C++


Java


Python



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 a preorder fashion 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 first node of the current level, and we print it and update the last level to the current level.

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

C++


Download  Run Code

Output:

1 2 4 7

Java


Download  Run Code

Output:

1 2 4 7

Python


Download  Run Code

Output:

1 2 4 7

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 right view of a binary tree