Left View of a Binary Tree

A Binary Tree's left view is a collection of the level's leftmost nodes.

Example:

Input:

Left View of a Binary Tree

Output:

4 5 3 6

Method 1: Iterative Implementation

Perform a level order traversal on the tree in the iterative version. To keep nodes at the current level, we can change the level order traversal. Print the current node if it is the first node in the current level.

Method 2: Using Recursion

The approach is to use recursion to find the binary tree's left view. A parameter can be passed to all recursive calls to determine a node's level. When we come across a node with a level greater than the highest level found thus far, we display it. This is due to the fact that it is the first node encountered at this level. We must traverse in such a way that the left subtree is visited before the right subtree in order to display the left view of a binary tree.

Program:

Output:

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

Hashing can also be used in a recursive implementation.

We can also use hashing to solve this problem. The plan is to preorder the tree's traversal while passing function arguments with level information. If the level is visited for the first time, add the information about the current node and level to the map. After processing each node, navigate the map and print the left view.

Program:

C++:

Java:

Output:

For the following input:

   1
 /  \
3    2

Output is: 1 3

What exactly is level order traversal?

The process of traversing a tree level by level is known as level order traversal.

Can we use preorder traversal to find the left view of a binary tree?

Yes, we only need to keep track of a node's current height, and if we visit a height for the first time, we'll print that element out.

Therefore, the left view of a binary tree can be implemented both in iterative and recursive ways.






Latest Courses