Iterative Method To Print Left View of a Binary Tree

Given a Binary Tree, print it’s left view. Left view of a Binary Tree is a set of nodes visible when tree is seen from the left side .

Examples:

Input :        1
             /   \
            2     3
           / \   / \
          4   5 6   7
Output : 1 2 4

Input :         1
              /   \
             2     3
              \   /
               4 5
                  \
                   6
                  / \
                 7   8
Output : 1 2 4 6 7


We have already discussed this problem using the Recursion method, here iterative approach is used to solve the above problem.

The idea is to do level order traversal of the Tree using a queue and print the first node at each level.

While doing level order traversal, after traversing all node at each level, push a NULL delimiter to mark the end of the current level. So, do the level order traversal of the tree. Print the first node at each level in the tree and push the children of all nodes at each level in the queue until a NULL delimiter is encountered.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print the
// left view of Binary Tree
  
#include <bits/stdc++.h>
  
using namespace std;
  
// A Binary Tree Node
struct node {
    int data;
    struct node *left, *right;
};
  
// A utility function to create a new
// Binary Tree node
struct node* newNode(int item)
{
    struct node* temp = new node;
    temp->data = item;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
  
// Utility function to print the left view of
// the binary tree
void leftViewUtil(struct node* root, queue<node*>& q)
{
    if (root == NULL)
        return;
  
    // Push root
    q.push(root);
  
    // Delimiter
    q.push(NULL);
  
    while (!q.empty()) {
        node* temp = q.front();
  
        if (temp) {
  
            // Prints first node
            // of each level
            cout << temp->data << " ";
  
            // Push children of all nodes at
            // current level
            while (q.front() != NULL) {
  
                // If left child is present
                // push into queue
                if (temp->left)
                    q.push(temp->left);
  
                // If right child is present
                // push into queue
                if (temp->right)
                    q.push(temp->right);
  
                // Pop the current node
                q.pop();
  
                temp = q.front();
            }
  
            // Push delimiter
            // for the next level
            q.push(NULL);
        }
  
        // Pop the delimiter of
        // the previous level
        q.pop();
    }
}
  
// Fucntion to print the leftView
// of Binary Tree
void leftView(struct node* root)
{
    // Queue to store all
    // the nodes of the tree
    queue<node*> q;
  
    leftViewUtil(root, q);
}
  
// Driver Code
int main()
{
    struct node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(3);
    root->left->right = newNode(4);
    root->right->left = newNode(5);
    root->right->left->right = newNode(6);
    root->right->left->right->left = newNode(18);
    root->right->left->right->right = newNode(7);
  
    leftView(root);
  
    return 0;
}

chevron_right


Python3

# Python3 program to print the
# left view of Binary Tree

# Binary Tree Node
“”” utility that allocates a newNode
with the given key “””
class newNode:

# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
self.hd=0

# Utility function to print the left
# view of the binary tree
def leftViewUtil(root, q) :

if (root == None) :
return

# append root
q.append(root)

# Delimiter
q.append(None)

while (len(q)):
temp = q[0]

if (temp):

# Prints first node of each level
print(temp.data, end = ” “)

# append children of all nodes
# at current level
while (q[0] != None) :
temp = q[0]

# If left child is present
# append into queue
if (temp.left) :
q.append(temp.left)

# If right child is present
# append into queue
if (temp.right) :
q.append(temp.right)

# Pop the current node
q.pop(0)

# append delimiter
# for the next level
q.append(None)

# Pop the delimiter of
# the previous level
q.pop(0)

# Fucntion to print the leftView
# of Binary Tree
def leftView(root):

# Queue to store all
# the nodes of the tree
q = []

leftViewUtil(root, q)

# Driver Code
if __name__ == ‘__main__’:

root = newNode(10)
root.left = newNode(12)
root.right = newNode(3)
root.left.right = newNode(4)
root.right.left = newNode(5)
root.right.left.right = newNode(6)
root.right.left.right.left = newNode(18)
root.right.left.right.right = newNode(7)
leftView(root)

# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Output:

10 12 4 6 18


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SHUBHAMSINGH10