Given the root of a binary tree. Return the left view of the binary tree. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left side.
Note:Â If the tree is empty, return an empty list.
Examples:
Input: root = [1, 2, 3, 4, 5, N, N]
Output: [1, 2, 4] Explanation: From the left side of the tree, only the nodes 1, 2, and 4 are visible.
Input: root = [1, 2, 3, N, N, 4, N, N, 5, N, N]
Output: [1, 2, 4, 5] Explanation: From the left side of the tree, only the nodes 1, 2, 4, and 5 are visible.
Level Order Traversal (BFS) - O(n) Time and O(n) Space
The idea is to traverse the tree level by level using a queue. At each level, the first node processed is the leftmost node, so we add it to the answer.
Working of Approach:
If the tree is empty, return an empty vector.
Perform level order traversal using a queue.
Process one level at a time.
Store the first node of every level in the result.
Continue until all levels are traversed.
C++
#include<iostream>#include<queue>#include<sstream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};vector<int>leftView(Node*root){vector<int>res;// If the tree is emptyif(root==nullptr)returnres;queue<Node*>q;q.push(root);// Perform level order traversalwhile(!q.empty()){intlevelSize=q.size();for(inti=0;i<levelSize;i++){Node*curr=q.front();q.pop();// First node of current level is part of left viewif(i==0)res.push_back(curr->data);// Push left childif(curr->left)q.push(curr->left);// Push right childif(curr->right)q.push(curr->right);}}returnres;}intmain(){// 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>ans=leftView(root);cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i!=ans.size()-1)cout<<", ";}cout<<"]";return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;classNode{publicintdata;publicNodeleft;publicNoderight;Node(intval){data=val;left=right=null;}}publicclassGFG{publicstaticArrayList<Integer>leftView(Noderoot){ArrayList<Integer>res=newArrayList<>();// If the tree is emptyif(root==null)returnres;Queue<Node>q=newLinkedList<>();q.add(root);// Perform level order traversalwhile(!q.isEmpty()){intlevelSize=q.size();for(inti=0;i<levelSize;i++){Nodecurr=q.poll();// First node of current level is part of// left viewif(i==0)res.add(curr.data);// Push left childif(curr.left!=null)q.add(curr.left);// Push right childif(curr.right!=null)q.add(curr.right);}}returnres;}publicstaticvoidmain(String[]args){// 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>ans=leftView(root);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i!=ans.size()-1)System.out.print(", ");}System.out.print("]");}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefleftView(root):res=[]# If the tree is emptyifrootisNone:returnresq=deque([root])# Perform level order traversalwhileq:levelSize=len(q)foriinrange(levelSize):curr=q.popleft()# First node of current level is part of left viewifi==0:res.append(curr.data)# Push left childifcurr.left:q.append(curr.left)# Push right childifcurr.right:q.append(curr.right)returnresif__name__=='__main__':# 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)ans=leftView(root)print('[',end='')foriinrange(len(ans)):print(ans[i],end='')ifi!=len(ans)-1:print(', ',end='')print(']')
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticList<int>leftView(Noderoot){List<int>res=newList<int>();// If the tree is emptyif(root==null)returnres;Queue<Node>q=newQueue<Node>();q.Enqueue(root);// Perform level order traversalwhile(q.Count>0){intlevelSize=q.Count;for(inti=0;i<levelSize;i++){Nodecurr=q.Dequeue();// First node of current level is part of// left viewif(i==0)res.Add(curr.data);// Push left childif(curr.left!=null)q.Enqueue(curr.left);// Push right childif(curr.right!=null)q.Enqueue(curr.right);}}returnres;}publicstaticvoidMain(){// 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>ans=leftView(root);Console.Write('[');for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i!=ans.Count-1)Console.Write(", ");}Console.Write(']');}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionleftView(root){letres=[];// If the tree is emptyif(root===null)returnres;letq=[];q.push(root);// Perform level order traversalwhile(q.length>0){letlevelSize=q.length;for(leti=0;i<levelSize;i++){letcurr=q.shift();// First node of current level is part of left// viewif(i===0)res.push(curr.data);// Push left childif(curr.left!==null)q.push(curr.left);// Push right childif(curr.right!==null)q.push(curr.right);}}returnres;}// Driver Code// 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);letans=leftView(root);console.log("[");for(leti=0;i<ans.length;i++){process.stdout.write(ans[i].toString());if(i!==ans.length-1)process.stdout.write(", ");}console.log("]");
Output
[1, 2, 4, 5]
DFS (Preorder Traversal) - O(n) Time and O(h) Space
The idea is to perform a preorder DFS traversal while keeping track of the current level. Since the left subtree is visited before the right subtree, the first node visited at every level forms the left view.
Working of Approach:
Start DFS from the root with level 0.
If a level is visited for the first time, store the current node.
Traverse the left subtree before the right subtree.
The first node reached at every level becomes part of the left view.
Continue recursively until all nodes are visited.
Let us understand with an example: Input: root = [1, 2, 3, N, N, 4, N, N, 5, N, N]
Start DFS from the root (1) at level 0. Since this is the first node at level 0, add 1 to the result.
Move to the left child (2) at level 1. It is the first node at this level, so add 2 to the result.
The left subtree of 2 is empty, so backtrack and visit the right subtree of the root (3). Since level 1 is already visited, do not add 3.
Traverse to node 4 at level 2. It is the first node at this level, so add 4 to the result. Then visit node 5 at level 3 and add it as the first node of that level.
The traversal ends, and the final left view is [1, 2, 4, 5].
C++
#include<iostream>#include<queue>#include<sstream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};voidrecLeftView(Node*root,intlevel,vector<int>&res){if(root==nullptr)return;// first node of current levelif(level==res.size()){res.push_back(root->data);}recLeftView(root->left,level+1,res);recLeftView(root->right,level+1,res);}vector<int>leftView(Node*root){vector<int>res;recLeftView(root,0,res);returnres;}intmain(){// Hardcoded 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>ans=leftView(root);cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i!=ans.size()-1)cout<<", ";}cout<<"]";return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticvoidrecLeftView(Noderoot,intlevel,ArrayList<Integer>res){if(root==null)return;// first node of current levelif(level==res.size()){res.add(root.data);}recLeftView(root.left,level+1,res);recLeftView(root.right,level+1,res);}publicstaticArrayList<Integer>leftView(Noderoot){ArrayList<Integer>res=newArrayList<>();recLeftView(root,0,res);returnres;}publicstaticvoidmain(String[]args){// 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>ans=leftView(root);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i!=ans.size()-1)System.out.print(", ");}System.out.print("]");}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefrecLeftView(root,level,res):ifrootisNone:return# first node of current leveliflevel==len(res):res.append(root.data)recLeftView(root.left,level+1,res)recLeftView(root.right,level+1,res)defleftView(root):res=[]recLeftView(root,0,res)returnresif__name__=='__main__':# 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)ans=leftView(root)print('[',end='')foriinrange(len(ans)):print(ans[i],end='')ifi!=len(ans)-1:print(', ',end='')print(']')
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticvoidrecLeftView(Noderoot,intlevel,List<int>res){if(root==null)return;// first node of current levelif(level==res.Count){res.Add(root.data);}recLeftView(root.left,level+1,res);recLeftView(root.right,level+1,res);}publicstaticList<int>leftView(Noderoot){List<int>res=newList<int>();recLeftView(root,0,res);returnres;}publicstaticvoidMain(){// 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>ans=leftView(root);Console.Write('[');for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i!=ans.Count-1)Console.Write(", ");}Console.Write(']');}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionrecLeftView(root,level,res){if(root===null){return;}// first node of current levelif(level===res.length){res.push(root.data);}recLeftView(root.left,level+1,res);recLeftView(root.right,level+1,res);}functionleftView(root){letres=[];recLeftView(root,0,res);returnres;}// 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);letans=leftView(root);console.log("[");for(leti=0;i<ans.length;i++){process.stdout.write(ans[i].toString());if(i!==ans.length-1){process.stdout.write(", ");}}console.log("]");