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
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)