Javatpoint Logo
Javatpoint Logo

Left View of a Binary Tree in Java

In this section, we will learn about the left view of a binary tree in Java with different approaches to achieve it. In the left view of a binary tree, we print only those nodes of the binary tree that are visible when the binary tree is viewed from the left.

Foe example, consider the following binary tree.

Left View of a Binary Tree in Java

The left view for the above binary tree is:

Note: In the left view of a binary tree, the order in which the nodes are displayed in the output is not relevant. All one should care about is that all of the nodes that are visible from the left side of the binary tree should be included in the output.

Approach 1: Using Recursion

The approach is to use the recursion to find the left view of the binary tree. A parameter can be passed to all of the recursive calls to find the level of a node. Whenever we come across a node whose level is more than the maximum level found so far, we display that node. It is because it is the first node encountered at this level. Since we have to display the left view of a binary tree, we have to traverse in such a way that the left subtree is visited before the right subtree.

Implementation

Let's see the implementation of the left view of a binary tree using recursion. The following code takes the O(n) time to complete its job, and the space complexity of the program is also O(n) because of the stack used in the recursive calls, where n is the total number of nodes present in the binary tree.

FileName: LeftViewExample.java

Output:

The following are the nodes present in the left view of the Binary Tree: 
20 22 25 14 7

Approach 2: Using Queue()

If we observe carefully, we will find that the left view of a binary tree is the first node encountered at every level. Therefore, we can use the queue data structure to traverse each level of the binary tree. At each level, we print only the value of the first node found at each level.

Implementation

Let's see the implementation of the left view of a binary tree using the queue. The time complexity of the below program is O(n), where n is the total number of nodes present in the tree.

FileName: LeftViewExample1.java

Output:

The following are the nodes present in the left view of the Binary Tree: 
20 22 25 14 7






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA