Skip to content

Commit b90c813

Browse files
authored
Tree Left View
1 parent 3dd54e8 commit b90c813

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Hacker Blocks/Tree Left View.cpp

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/* Hacker Blocks */
2+
/* Title - Tree Left View */
3+
/* Created By - Akash Modak */
4+
/* Date - 26/10/2020 */
5+
6+
// Given a binary tree , print its nodes from root to bottom as visible from left side of tree
7+
8+
// Input Format
9+
// Level order input for the binary tree will be given.
10+
11+
// Constraints
12+
// No of nodes in the tree can be less than or equal to 10^7
13+
14+
// Output Format
15+
// A single line containing space separated integers representing the left view of the tree
16+
17+
// Sample Input
18+
// 1 2 3 4 5 -1 6 -1 -1 -1 -1 -1 -1
19+
// Sample Output
20+
// 1 2 4
21+
// Explanation
22+
// The tree looks like
23+
24+
// 1
25+
// / \
26+
// 2 3
27+
// / \ \
28+
// 4 5 6
29+
// When viewed from the left , we would see the nodes 1,2 and 4.
30+
31+
#include<bits/stdc++.h>
32+
using namespace std;
33+
class node{
34+
public: int data;
35+
node* left,*right;
36+
node(int d){
37+
data = d;
38+
left = right = NULL;
39+
}
40+
};
41+
42+
void leftView(node* root){
43+
queue<node*> q;
44+
q.push(root);
45+
while(!q.empty()){
46+
int n = q.size();
47+
for(int i=0;i<n;i++){
48+
node* temp = q.front();
49+
q.pop();
50+
if(i==0)
51+
cout<<temp->data<<" ";
52+
53+
if(temp->left)
54+
q.push(temp->left);
55+
if(temp->right)
56+
q.push(temp->right);
57+
}
58+
}
59+
return;
60+
}
61+
void leftViewRecur(node* root,int level,int *maxLevel){
62+
if(root==NULL)
63+
return;
64+
65+
if(*maxLevel<level){
66+
cout<<root->data<<" ";
67+
*maxLevel = level;
68+
}
69+
leftViewRecur(root->left,level+1,maxLevel);
70+
leftViewRecur(root->right,level+1,maxLevel);
71+
}
72+
73+
node* create(){
74+
int d;
75+
cin>>d;
76+
if(d==-1)
77+
return NULL;
78+
node* root = new node(d);
79+
queue<node*> q;
80+
q.push(root);
81+
while(!q.empty()){
82+
node* temp = q.front();
83+
q.pop();
84+
cin>>d;
85+
if(d!=-1){
86+
temp->left = new node(d);
87+
q.push(temp->left);
88+
}
89+
cin>>d;
90+
if(d!=-1){
91+
temp->right = new node(d);
92+
q.push(temp->right);
93+
}
94+
}
95+
return root;
96+
}
97+
int main() {
98+
node* root = create();
99+
leftView(root);
100+
int m = 0;
101+
// inorder(root); cout<<endl;
102+
// leftViewRecur(root,1,&m);
103+
return 0;
104+
}

0 commit comments

Comments
 (0)