-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram-1.cpp
More file actions
105 lines (85 loc) · 1.94 KB
/
program-1.cpp
File metadata and controls
105 lines (85 loc) · 1.94 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
TBT Creation and Preorder Traversal
*/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
bool lthread, rthread;
Node(int val) {
data = val;
left = right = NULL;
lthread = rthread = true;
}
};
class TBT {
Node* root;
public:
TBT() {
root = NULL;
}
void insert(int key) {
Node* ptr = root;
Node* par = NULL;
while (ptr != NULL) {
if (key == ptr->data)
return;
par = ptr;
if (key < ptr->data) {
if (!ptr->lthread)
ptr = ptr->left;
else
break;
} else {
if (!ptr->rthread)
ptr = ptr->right;
else
break;
}
}
Node* temp = new Node(key);
if (par == NULL) {
root = temp;
temp->left = temp->right = NULL;
} else if (key < par->data) {
temp->left = par->left;
temp->right = par;
par->lthread = false;
par->left = temp;
} else {
temp->left = par;
temp->right = par->right;
par->rthread = false;
par->right = temp;
}
}
void preorder() {
Node* cur = root;
while (cur != NULL) {
cout << cur->data << " ";
if (!cur->lthread)
cur = cur->left;
else if (!cur->rthread)
cur = cur->right;
else {
while (cur != NULL && cur->rthread)
cur = cur->right;
if (cur != NULL)
cur = cur->right;
}
}
}
};
int main() {
TBT t;
int n, x;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
t.insert(x);
}
t.preorder();
return 0;
}