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++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node *left, *right;
};
struct node* newNode( int item)
{
struct node* temp = new node;
temp->data = item;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void leftViewUtil( struct node* root, queue<node*>& q)
{
if (root == NULL)
return ;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node* temp = q.front();
if (temp) {
cout << temp->data << " " ;
while (q.front() != NULL) {
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
q.pop();
temp = q.front();
}
q.push(NULL);
}
q.pop();
}
}
void leftView( struct node* root)
{
queue<node*> q;
leftViewUtil(root, q);
}
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;
}
|
Java
import java.util.*;
class GFG
{
static class node
{
int data;
node left, right;
};
static node newNode( int item)
{
node temp = new node();
temp.data = item;
temp.left = null ;
temp.right = null ;
return temp;
}
static Queue<node> q;
static void leftViewUtil( node root )
{
if (root == null )
return ;
q.add(root);
q.add( null );
while (q.size() > 0 )
{
node temp = q.peek();
if (temp != null )
{
System.out.print(temp.data + " " );
while (q.peek() != null )
{
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
q.remove();
temp = q.peek();
}
q.add( null );
}
q.remove();
}
}
static void leftView( node root)
{
q = new LinkedList<node>();
leftViewUtil(root);
}
public static void main(String args[])
{
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);
}
}
|
Python3
class newNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
self .hd = 0
def leftViewUtil(root, q) :
if (root = = None ) :
return
q.append(root)
q.append( None )
while ( len (q)):
temp = q[ 0 ]
if (temp):
print (temp.data, end = " " )
while (q[ 0 ] ! = None ) :
temp = q[ 0 ]
if (temp.left) :
q.append(temp.left)
if (temp.right) :
q.append(temp.right)
q.pop( 0 )
q.append( None )
q.pop( 0 )
def leftView(root):
q = []
leftViewUtil(root, q)
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)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class node
{
public int data;
public node left, right;
};
static node newNode( int item)
{
node temp = new node();
temp.data = item;
temp.left = null ;
temp.right = null ;
return temp;
}
static Queue<node> q = new Queue<node>();
static void leftViewUtil( node root )
{
if (root == null )
return ;
q.Enqueue(root);
q.Enqueue( null );
while (q.Count > 0)
{
node temp = q.Peek();
if (temp != null )
{
Console.Write(temp.data + " " );
while (q.Peek() != null )
{
if (temp.left != null )
q.Enqueue(temp.left);
if (temp.right != null )
q.Enqueue(temp.right);
q.Dequeue();
temp = q.Peek();
}
q.Enqueue( null );
}
q.Dequeue();
}
}
static void leftView( node root)
{
q = new Queue<node>();
leftViewUtil(root);
}
public static void Main(String []args)
{
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);
}
}
|
Javascript
<script>
class node
{
constructor(item) {
this .left = null ;
this .right = null ;
this .data = item;
}
}
function newNode(item)
{
let temp = new node(item);
return temp;
}
let q = [];
function leftViewUtil(root)
{
if (root == null )
return ;
q.push(root);
q.push( null );
while (q.length > 0)
{
let temp = q[0];
if (temp != null )
{
document.write(temp.data + " " );
while (q[0] != null )
{
if (temp.left != null )
q.push(temp.left);
if (temp.right != null )
q.push(temp.right);
q.shift();
temp = q[0];
}
q.push( null );
}
q.shift();
}
}
function leftView(root)
{
q = [];
leftViewUtil(root);
}
let 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);
</script>
|
Complexity Analysis:
- Time Complexity: O(N) where N is the number of vertices in the binary tree.
- Auxiliary Space: O(N).
Iterative Approach(using Stack):
To print the left view of a binary tree without using a queue, we can use an iterative approach that performs a level-order traversal of the tree and prints the first node encountered at each level. Here’s an algorithm that outlines the steps:
1) If the root is null, return.
2) Initialize a variable called “currentLevel” to 1.
3) Create a stack and push the root onto it.
4) While the stack is not empty:
a. Initialize a variable called “levelSize” to the size of the stack.
b. Initialize a boolean variable called “foundLeftMost” to false.
c. Loop through the stack from top to bottom, popping each node and pushing its children onto the stack (if they exist) in reverse order (right child first, then left child). For each node encountered, check if it is the first node encountered at its level. If so, print its value and set “foundLeftMost” to true.
d. If “foundLeftMost” is true, break out of the loop.
e. Increment “currentLevel” by 1.
5) Return.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left, *right;
};
struct Node* newNode( int key)
{
struct Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
void print_left_view(Node* root)
{
if (root == NULL) return ;
queue<Node*> stack;
stack.push(root);
while (!stack.empty()) {
int levelSize = stack.size();
bool foundLeftMost = false ;
for ( int i = 0; i < levelSize; i++) {
Node* node = stack.front();
stack.pop();
if (!foundLeftMost) {
cout << node->data << " " ;
foundLeftMost = true ;
}
if (node->left != NULL) {
stack.push(node->left);
}
if (node->right != NULL) {
stack.push(node->right);
}
}
}
}
int main()
{
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);
print_left_view(root);
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
public Node( int data) {
this .data = data;
left = right = null ;
}
}
public class Main {
static void print_left_view(Node root) {
if (root == null ) return ;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
boolean foundLeftMost = false ;
for ( int i = 0 ; i < levelSize; i++) {
Node node = queue.poll();
if (!foundLeftMost) {
System.out.print(node.data + " " );
foundLeftMost = true ;
}
if (node.left != null ) {
queue.add(node.left);
}
if (node.right != null ) {
queue.add(node.right);
}
}
}
}
public static void main(String[] args) {
Node root = new Node( 10 );
root.left = new Node( 12 );
root.right = new Node( 3 );
root.left.right = new Node( 4 );
root.right.left = new Node( 5 );
root.right.left.right = new Node( 6 );
root.right.left.right.left = new Node( 18 );
root.right.left.right.right = new Node( 7 );
print_left_view(root);
}
}
|
Python3
class newNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def print_left_view(root):
if root is None :
return
stack = []
stack.append(root)
while stack:
levelSize = len (stack)
foundLeftMost = False
for i in range (levelSize):
node = stack.pop( 0 )
if not foundLeftMost:
print (node.data)
foundLeftMost = True
if (node.left is not None ):
stack.append(node.left)
if (node.right is not None ):
stack.append(node.right)
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 )
print_left_view(root)
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
public class Program
{
static void print_left_view(Node root)
{
if (root == null ) return ;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count > 0)
{
int levelSize = queue.Count;
bool foundLeftMost = false ;
for ( int i = 0; i < levelSize; i++)
{
Node node = queue.Dequeue();
if (!foundLeftMost)
{
Console.Write(node.data + " " );
foundLeftMost = true ;
}
if (node.left != null )
{
queue.Enqueue(node.left);
}
if (node.right != null )
{
queue.Enqueue(node.right);
}
}
}
}
public static void Main( string [] args)
{
Node root = new Node(10);
root.left = new Node(12);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.left.right = new Node(6);
root.right.left.right.left = new Node(18);
root.right.left.right.right = new Node(7);
print_left_view(root);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function print_left_view(root) {
if (root === null ) return ;
let queue = [];
queue.push(root);
while (queue.length !== 0) {
let levelSize = queue.length;
let foundLeftMost = false ;
for (let i = 0; i < levelSize; i++) {
let node = queue.shift();
if (!foundLeftMost) {
console.log(node.data + " " );
foundLeftMost = true ;
}
if (node.left !== null ) {
queue.push(node.left);
}
if (node.right !== null ) {
queue.push(node.right);
}
}
}
}
let root = new Node(10);
root.left = new Node(12);
root.right = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.left.right = new Node(6);
root.right.left.right.left = new Node(18);
root.right.left.right.right = new Node(7);
print_left_view(root);
|
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to stack data structure.
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...