-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search_tree.c
128 lines (100 loc) · 2.6 KB
/
binary_search_tree.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
double value;
struct node *left_child;
struct node *right_child;
} node;
node *copy_tree(node *root);
node *create_node(double value);
node *find_value(node *root, double value);
void add_element(node **root_ptr, double value);
void print_tree(node *root);
void destroy(node *root);
int main(void) {
node *root = NULL;
add_element(&root, 15);
add_element(&root, 11);
add_element(&root, 24);
add_element(&root, 19);
add_element(&root, 20);
add_element(&root, 5);
add_element(&root, 7);
print_tree(root);
find_value(root, 5);
node *second = copy_tree(root);
destroy(root);
printf("\n\n\nSecond:\n");
print_tree(second);
return 0;
}
node *create_node(double value) {
node *new_node = malloc(sizeof(node));
if (new_node != NULL) {
new_node->left_child = NULL;
new_node->right_child = NULL;
new_node->value = value;
}
return new_node;
}
void print_tree(node *root) {
if (root == NULL) {
printf("<empty>\n");
return;
}
printf("%f\n", root->value);
printf("Left: \n");
print_tree(root->left_child);
printf("Right: \n");
print_tree(root->right_child);
printf("Done\n");
}
void add_element(node **root_ptr, double value) {
node *root = *root_ptr;
if (root == NULL) {
(*root_ptr) = create_node(value);
return;
} // If there is no root - create one
if (value == root->value) {
printf("Value already in the tree ... ");
return;
} // If value already exists - do nothing
if (value < root->value) {
add_element(&(root->left_child), value);
} else {
add_element(&(root->right_child), value);
}
}
node *find_value(node *root, double value) {
node *temp = root;
if (temp == NULL) {
printf("Tree is empty ...\n");
return NULL;
}
if (temp->value == value) {
printf("Found %f at address: %p\n", value, temp);
return temp;
}
if (value > temp->value) {
return find_value(temp->right_child, value);
} else {
return find_value(temp->left_child, value);
}
}
void destroy(node *root) {
if (root == NULL) {
return;
}
destroy(root->left_child);
destroy(root->right_child);
free(root);
}
node *copy_tree(node *root) {
if (root == NULL) {
return NULL;
}
node *new_node = create_node(root->value);
new_node->left_child = copy_tree(root->left_child);
new_node->right_child = copy_tree(root->right_child);
return new_node;
}