[Approach - 1] Using Depth-first search (DFS) - O(n) Time and O(n) Space
The idea is to use DFS and Keep track of current level. For every level of the binary tree, the first node we see from the left side is part of the left view.
C++
#include<iostream>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Recursive function to find left viewvoidrecLeftView(Node*root,intlevel,vector<int>&result){if(root==nullptr)return;// first node of current levelif(level==result.size()){result.push_back(root->data);}recLeftView(root->left,level+1,result);recLeftView(root->right,level+1,result);}// Function which return left view of binary treevector<int>leftView(Node*root){vector<int>result;recLeftView(root,0,result);returnresult;}intmain(){// Create binary tree// 1// / \ // 2 3// /// 4// \ // 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->left->right=newNode(5);vector<int>view=leftView(root);for(intval:view)cout<<val<<" ";}
Java
importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Recursive function to find left viewstaticvoidrecLeftView(Noderoot,intlevel,ArrayList<Integer>result){if(root==null)return;// first node of current levelif(level==result.size()){result.add(root.data);}recLeftView(root.left,level+1,result);recLeftView(root.right,level+1,result);}// Function which return left view of binary treestaticArrayList<Integer>leftView(Noderoot){ArrayList<Integer>result=newArrayList<>();recLeftView(root,0,result);returnresult;}publicstaticvoidmain(String[]args){// Create binary tree// 1// / \// 2 3// /// 4// \// 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);ArrayList<Integer>view=leftView(root);for(intval:view)System.out.print(val+" ");}}
Python
# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to find left viewdefrecLeftView(root,level,result):ifrootisNone:return# first node of current leveliflevel==len(result):result.append(root.data)recLeftView(root.left,level+1,result)recLeftView(root.right,level+1,result)# Function which return left view of binary treedefleftView(root):result=[]recLeftView(root,0,result)returnresultif__name__=="__main__":# Create binary tree# 1# / \# 2 3# /# 4# \# 5root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.left.right=Node(5)result=leftView(root)print(*result);
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Recursive function to find left viewstaticvoidrecLeftView(Noderoot,intlevel,List<int>result){if(root==null)return;// first node of current levelif(level==result.Count){result.Add(root.data);}recLeftView(root.left,level+1,result);recLeftView(root.right,level+1,result);}// Function which return left view of binary treestaticList<int>leftView(Noderoot){List<int>result=newList<int>();recLeftView(root,0,result);returnresult;}staticvoidMain(string[]args){// Create binary tree// 1// / \// 2 3// /// 4// \// 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);List<int>view=leftView(root);foreach(intvalinview){Console.Write(val+" ");}}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to find left viewfunctionrecLeftView(root,level,result){if(root===null)return;// first node of current levelif(level===result.length){result.push(root.data);}recLeftView(root.left,level+1,result);recLeftView(root.right,level+1,result);}// Function which return left view of binary treefunctionleftView(root){constresult=[];recLeftView(root,0,result);returnresult;}// Driver Code// Create binary tree// 1// / \// 2 3// /// 4// \// 5constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);constresult=leftView(root);console.log(...result);
Output
1 2 4 5
[Approach - 2] Using Level Order Traversal (BFS) - O(n) Time and O(n) Space
The left view contains all nodes that are the first nodes in their levels. A simple solution is to do level order traversal and print the first nodein every level.
C++
#include<iostream>#include<vector>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};vector<int>leftView(Node*root){if(root==nullptr)return{};// Queue for level order traversalqueue<Node*>q;vector<int>res;q.push(root);while(!q.empty()){intlevelSize=q.size();for(inti=0;i<levelSize;i++){Node*curr=q.front();q.pop();// If it's the first node of the current levelif(i==0)res.push_back(curr->data);if(curr->left!=nullptr)q.push(curr->left);if(curr->right!=nullptr)q.push(curr->right);}}returnres;}intmain(){// Create binary tree// 1// / \ // 2 3// /// 4// \ // 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->left->right=newNode(5);vector<int>res=leftView(root);for(intnode:res)cout<<node<<" ";}
Java
importjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{staticArrayList<Integer>leftView(Noderoot){if(root==null)returnnewArrayList<>();// Queue for level order traversalQueue<Node>q=newLinkedList<>();ArrayList<Integer>res=newArrayList<>();q.add(root);while(!q.isEmpty()){intlevelSize=q.size();for(inti=0;i<levelSize;i++){Nodecurr=q.poll();// If it's the first node of the current levelif(i==0)res.add(curr.data);if(curr.left!=null){q.add(curr.left);}if(curr.right!=null){q.add(curr.right);}}}returnres;}publicstaticvoidmain(String[]args){// Create binary tree// 1// / \// 2 3// /// 4// \// 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);ArrayList<Integer>res=leftView(root);for(intnode:res)System.out.print(node+" ");}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefleftView(root):ifrootisNone:return[]# Queue for level order traversalq=deque()res=[]q.append(root)whileq:levelSize=len(q)foriinrange(levelSize):curr=q.popleft()# If it's the first node of the current levelifi==0:res.append(curr.data)ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)returnresif__name__=="__main__":# Create binary tree# 1# / \# 2 3# /# 4# \# 5root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.left.right=Node(5)res=leftView(root)print(*res)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{staticList<int>leftView(Noderoot){if(root==null)returnnewList<int>();// Queue for level order traversalQueue<Node>q=newQueue<Node>();List<int>res=newList<int>();q.Enqueue(root);while(q.Count>0){intlevelSize=q.Count;for(inti=0;i<levelSize;i++){Nodecurr=q.Dequeue();// If it's the first node of the current levelif(i==0)res.Add(curr.data);if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}}returnres;}staticvoidMain(string[]args){// Create binary tree// 1// / \// 2 3// /// 4// \// 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);List<int>res=leftView(root);foreach(intnodeinres)Console.Write(node+" ");}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Custom Queue ImplementationclassQueue{constructor(){this.items={};this.headIndex=0;this.tailIndex=0;}enqueue(item){this.items[this.tailIndex]=item;this.tailIndex++;}dequeue(){if(this.isEmpty())returnnull;letitem=this.items[this.headIndex];deletethis.items[this.headIndex];this.headIndex++;returnitem;}isEmpty(){returnthis.tailIndex===this.headIndex;}size(){returnthis.tailIndex-this.headIndex;}}functionleftView(root){if(!root)return[];// Queue for level order traversalletq=newQueue();letres=[];q.enqueue(root);while(!q.isEmpty()){letlevelSize=q.size();for(leti=0;i<levelSize;i++){letcurr=q.dequeue();// If it's the first node of the current levelif(i===0)res.push(curr.data);if(curr.left)q.enqueue(curr.left);if(curr.right)q.enqueue(curr.right);}}returnres;}// Driver code// Create binary tree// 1// / \// 2 3// /// 4// \// 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.left.right=newNode(5);letres=leftView(root);console.log(res.join(" "));