Print the left view of a binary tree

Posted by N.K. Chauhan on Mar 31, 2024

Given a binary tree, the task is to write an iterative and recursive solution to print left-view of it.

Example 1: Print left view of a Binary Tree

Input:

Output: 1, 7, 2, 5


Solutions

Method 1: Recursion

Printing left-view of a binary tree using recursion is straightforward, the idea is to do level order traversal and print the very first element of each level.

We can keep track of the level of a node by passing a parameter to all recursive calls.

We also need to keep track of "maximum level so far", whenever we see a node whose level is more than "maximum level so far", we print the node because this is the first node in its level (Note that we traverse the left subtree before right subtree).

maxLevel -> 0
leftView(root,level)
    if(root==null)
        return
    if(level>maxLevel)
        print(root)
    maxLevel -> level
    leftView(root.left,level+1)
    leftView(root.right,level+1)

Complexity
The time complexity of this solution is O(n) and space complexity is O(n) due to recursive calls.

Method 2: Iterative

We can print left-view of a binary tree with the help of a queue, the idea is to do level order traversal using a queue and print only the very first element of a level.

queue -> empty queue
queue.add(root)
while(non empty queue)
    n -> size(queue)
    for(int i=0;i<n;i++)
	Node node = queue.poll()
	if(i==0)
	    print(node)
	if(node.left!=null)
	    queue.add(node.left)
	if(node.right!=null)
	    queue.add(node.right)
Complexity
The time complexity of this solution is O(n) and space complexity is O(n) due to auxiliary queue.

Related


Write a program to print height/depth of a Binary Tree

Print Nodes in Top View of a Binary Tree

Print diagonal traversal of a binary tree

Create a mirror tree from a given binary tree

In-order Tree Traversal - Iterative and Recursive

Print a Binary Tree in Vertical Order

Print/Traverse a Binary Tree in Zigzag Order

Find the diameter or width of a binary tree

Pre-order Tree Traversal - Iterative and Recursive

Level Order or Breadth First traversal of Binary Tree