Left view of a binary tree

You are given a binary tree, you need to print the left view of it.

Consider the tree in the below figure.

The left view of the tree would be {8, 3, 1, 4}.


  1. Create a queue which would store the nodes of the tree. Insert the root node in the tree.
  2. While the queue is not empty, we do the following.
    Compute the size of the queue at each iteration. You need to print the first node of each level in the tree. At each iteration, loop for i = 1 to n.
    If i=1, it means that it is the first node of the level. Print the node and insert the left and right child to the queue and pop the current node. For all other nodes in the current level, push the left and right child of the current node and pop the node from the queue.

Check out the complete code in C++.

#include <bits/stdc++.h>

using namespace std;

struct Node{
  Node* left;
  Node* right;
  int data;

Node* createNode(int key){
    Node* temp = new Node();
    temp->data = key;
    temp->right = nullptr;
    temp->left = nullptr;
    return temp;

Node* root = nullptr;

Node* insertNode(Node* node, int key){
    Node* temp = createNode(key);
    if(root == nullptr){
        root = temp;
        return root;
    if(node == nullptr){
        return temp;   
    if(key < node->data){
        node->left = insertNode(node->left, key);
    }else if(key > node->data){
        node->right = insertNode(node->right, key);
    return node;

void leftView(Node* root){
    queue<Node*> q;
        int n = q.size();
        for(int i = 1; i <= n; i++){
            Node* temp = q.front();
                cout<<temp->data<<" ";

void levelOrderTraversal(){
    Node* temp = root;
    queue<Node*> q;
        Node* front = q.front();
        cout<<front->data<<" ";
        if(front->left != nullptr){
        if(front->right != nullptr){

int main()
    insertNode(root, 8);
    insertNode(root, 3);
    insertNode(root, 10);
    insertNode(root, 1);
    insertNode(root, 6);
    insertNode(root, 14);
    insertNode(root, 4);
    insertNode(root, 7);
    insertNode(root, 13);
    cout<<"Level order traversal: ";
    cout<<endl<<"Left view: ";
    return 0;

Also, check out another popular interview problem Construct a binary tree from preorder and postorder traversals.

One comment

Leave a Reply

Your email address will not be published.