Left View of a Binary Tree

Given a binary tree, write a code to print the left view of a binary tree.

Left View of a Binary Tree

The left view of a binary tree is the set of visible nodes when the tree is seen from the left side.

For Example –

Example 1 –

In the first example, When you see the binary tree from the left side the nodes which are visible are 4, 3, 1.

Example 2 –

In the second example, Nodes 9, 8, 1 are visible from the left side.

Print Left View of a Binary Tree using Queue

We have discussed the problem statement. Before checking the solution, Think about how you can approach this problem? Which tree traversal algorithm do you use to solve this problem.

Print Left View of a Binary Tree – Java Code

One way to solve this problem is to do a level order traversal of a binary tree and print the first node of each level. The idea here is to traverse a binary tree level by level and print the first node of each level.

The time and space complexity of this approach is O(n).

Here are the following steps to print the left view of the binary tree:

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 operations.

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

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

c) Dequeue a node from the queue and check if it’s the first 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.

iii) Repeat these steps until the complete traversal of a binary tree.

This problem is similar to the print right view of a binary tree.

Reverse level order traversal of a binary tree

Programming video tutorials

Left view of a binary tree video tutorial

Tree traversal algorithms –

Binary Tree Preorder Traversal

Binary Tree inorder traversal

Tagged . Bookmark the permalink.

About WebRewrite

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