-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
85 lines (78 loc) · 1.51 KB
/
tree.cpp
File metadata and controls
85 lines (78 loc) · 1.51 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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
void insert(Node* node, int data) {
if (data > node->data) {
if (node->right == NULL) {
Node* newNode = new Node;
node->right = newNode;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
} else {
insert(node->right, data);
}
} else {
if (node->left == NULL) {
Node* newNode = new Node;
node->left = newNode;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
} else {
insert(node->left, data);
}
}
}
void print_tree(Node* node) {
cout << node->data << endl;
if (node->left != NULL) {
print_tree(node->left);
} else {
return;
}
if (node->right != NULL) {
print_tree(node->right);
} else {
return;
}
}
void clean_up(Node* node) {
if (node->right != NULL) {
clean_up(node->right);
}
if (node->left != NULL) {
clean_up(node->left);
}
if (node->left == NULL && node->right ==NULL) {
delete node;
return;
}
}
int main(int argc, char* argv[]) {
bool done = false;
int to_insert;
Node node;
Node* root;
root = &node;
root->left = NULL;
root->right = NULL;
cout << "Input data:";
cin >> to_insert;
root->data = to_insert;
while (!done) {
cout << "Input data:";
cin >> to_insert;
if (to_insert == -100) {
done = true;
}
insert(root, to_insert);
print_tree(root);
}
clean_up(root);
return 0;
}