-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathLeftView_BinaryTree.cpp
More file actions
90 lines (78 loc) · 1.74 KB
/
LeftView_BinaryTree.cpp
File metadata and controls
90 lines (78 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node*left;
node*right;
node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree() {
int d;
cin >> d;
if (d == -1) {
return NULL;
}
node * root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
/////////******************METHOD-1***************////////////////
//Simple Pre Order traversal
int max_level = 0;
void leftViewRecursive(node* root, int level)
{
// base case
if (root == NULL)
return;
if (max_level < level)
{
cout << root->data << " ";
max_level = level;
}
leftViewRecursive(root->left, level + 1);
leftViewRecursive(root->right, level + 1);
}
/////////******************METHOD-2***************////////////////
//Simple Level Order traversal
vector<int> leftViewIterative(node* root)
{
queue<node*>q;
vector<int>ans;
if (root == NULL)
return ans;
q.push(root);
q.push(NULL);
ans.push_back(root->data);
while (q.size() > 1)
{
if (q.front() == NULL)
{
q.push(NULL);
q.pop();
ans.push_back(q.front()->data);
continue;
}
node* n = q.front();
if (n->left)
q.push(n->left);
if (n->right)
q.push(n->right);
q.pop();
}
return ans;
}
int main() {
node* root = buildTree();
leftViewRecursive(root, 1);
std::vector<int> ans = leftViewIterative(root);
cout << endl;
for (auto x : ans)
cout << x << " ";
return 0;
}