-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElements_btw_2_level_in_Binary_Tree_using_Queue.cpp
84 lines (60 loc) · 1.29 KB
/
Elements_btw_2_level_in_Binary_Tree_using_Queue.cpp
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
#include <bits/stdc++.h>
using namespace std;
unordered_map <int, int> um;
struct Node
{
int info;
struct Node *left, *right;
};
struct Node* create()
{
int data;
Node *tree;
tree = new Node;
cout << "\nEnter data to be inserted or type -1 : ";
cin >> data;
if(data == -1)
return 0;
tree->info = data;
cout << "Enter left child of " << data;
tree->left = create();
cout << "Enter right child of " << data;
tree->right = create();
return tree;
};
void printNodes(Node* root, int start, int end)
{
if(root == NULL)
return;
queue <Node*> q;
q.push(root);
Node* curr = NULL;
int level = 0;
while(!q.empty() || curr)
{
level++;
int size = q.size();
while(size--)
{
curr = q.front();
q.pop();
if(level >= start && level <= end)
cout<<curr->info<<" ";
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
}
if(level >= start && level <= end)
cout<<endl;
}
}
int main()
{
Node *root = NULL;
root = create();
int level1 = 2;
int level2 = 4;
printNodes(root, level1, level2);
return 0;
}