-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_BuildLvlOrderTree.cpp
More file actions
68 lines (68 loc) · 1.6 KB
/
04_BuildLvlOrderTree.cpp
File metadata and controls
68 lines (68 loc) · 1.6 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
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
class node {
public:
int data;
node *left, *right;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
void buildFromLevelOrder(node *&root) {
queue<node *> q;
int data;
cout << "Enter Data: ";
cin >> data;
root = new node(data);
q.push(root);
while (!q.empty()) {
node *temp = q.front();
q.pop();
int leftData, rightData;
cout << "Enter Left data for " << temp->data << " : ";
cin >> leftData;
if (leftData != -1) {
temp->left = new node(leftData);
q.push(temp->left);
}
cout << "Enter Right data for " << temp->data << " : ";
cin >> rightData;
if (rightData != -1) {
temp->right = new node(rightData);
q.push(temp->right);
}
}
}
void levelOrderTraversal(node *root) {
queue<node *> q;
q.push(root), q.push(NULL);
while (!q.empty()) {
node *temp = q.front();
q.pop();
if (temp == NULL) {
cout << endl;
if (!q.empty()) {
q.push(NULL);
}
} else {
cout << temp->data << " ";
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
}
int main() {
node *root = NULL;
buildFromLevelOrder(root);
cout << "Level Order Traversal:\n";
levelOrderTraversal(root);
return 0;
}