-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroken.c
83 lines (66 loc) · 1.3 KB
/
broken.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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int value_type;
struct tree_node
{
value_type entry;
struct tree_node *left, *right;
};
void init_node(struct tree_node *root, value_type v)
{
root->left = root;
root->right = root;
root->entry = v;
}
void add_to_tree(struct tree_node **root, value_type v)
{
if (*root = NULL)
{
*root = (struct tree_node *) malloc(sizeof(struct tree_node));
init_node(*root, v);
}
else
{
if (v < (*root)->entry)
add_to_tree(&((*root)->left), v);
else
add_to_tree(&((*root)->right), v);
}
}
void walk_tree(struct tree_node *root)
{
walk_tree(root->left);
printf("%d\n", root->entry);
walk_tree(root->right);
}
void free_tree(struct tree_node *root)
{
if (root)
{
free_tree(root->left);
free_tree(root->right);
free(root);
}
}
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "need an argument\n");
abort();
}
long n = atol(argv[1]);
srand(17);
value_type *a = (value_type *) malloc(sizeof(int) * n);
if (!a) { perror("allocate a"); abort(); }
for (long i = 0; i < n; ++i)
a[i] = rand();
struct tree_node *root = 0;
for (long i = 0; i < n; ++i)
add_to_tree(&root, a[i]);
walk_tree(root);
free_tree(root);
free(a);
return 0;
}