Print Left View of a Binary Tree in C++
In this tutorial, we are going to print the left view of a Binary Tree in C++.
Left View of a Binary Tree
The left view of a Tree is a set of nodes visible when the tree is looked at from the left side.
Examples:
1. 6
/ \
5 4
/ \ \
3 2 1
Output: 6 5 32. 1
/ \
2 3
\
4
/ \
5 6
\
7
Output: 1 2 4 5 7The task is to find all the nodes visible when looked at from the left side of the binary tree. The basic idea is to perform a level order traversal and then print the first element of each level.
Example :
6
/ \
5 4
/ \ \
3 2 1Level order traversal – [ [6],
[5, 4],
[3, 2, 1]
]
Now taking the first element of each level, we get 6 5 3. This is also the required output.
Printing left view of a binary tree in C++
Below is the implementation:
#include <iostream>
#include <queue>
#include <list>
using namespace std;
int max_level = 0;
class node
{
public: int data; node *left, *right;
};
node* newNode(int item)
{
node* temp = new node();
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void leftView(node* root)
{
if (root == NULL) return;
queue <node *> Q;
Q.push(root);
while(!Q.empty())
{
int size = Q.size();
for(int i = 0; i<size; i++)
{
node * temp = Q.front();
Q.pop();
if(i == 0)
{
cout << temp->data << " ";
}
if(temp->left != NULL)
{
Q.push(temp->left);
}
if(temp->right != NULL)
{
Q.push(temp->right);
}
}
}
}
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->left->right->left = newNode(5);
root->left->right->right = newNode(6);
root->left->right->right->right = newNode(7);
leftView(root);
return 0;
}
Output:
1 2 4 5 7
Also read:
Leave a Reply