-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path2.8.trees.c
121 lines (109 loc) · 2.74 KB
/
2.8.trees.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Namevel Namevel;
struct Namevel
{
char *name;
int value;
Namevel *left; // lesser
Namevel *right; // greater
};
// insert: insert newp in treep, return treep
Namevel *insert(Namevel *treep, Namevel *newp)
{
int cmp;
if (treep == NULL)
return newp;
cmp = strcmp(newp->name, treep->name);
if (cmp == 0)
{
printf("insert: duplicate entry %s ignored", newp->name);
return NULL;
}
else if (cmp < 0)
{
treep->left = insert(treep->left, newp);
}
else
{
treep->right = insert(treep->right, newp);
}
return treep;
}
// lookup: look up name in tree treep
Namevel *lookup(Namevel *treep, char *name)
{
int cmp;
if (treep == NULL)
return NULL;
cmp = strcmp(name, treep->name);
if (cmp == 0)
return treep;
else if (cmp < 0)
return lookup(treep->left, name);
else
return lookup(treep->right, name);
}
// nrlookup: non-recursively look up name in tree treep
Namevel *nrlookup(Namevel *treep, char *name)
{
int cmp;
while (treep != NULL)
{
cmp = strcmp(name, treep->name);
if (cmp == 0)
return treep;
else if (cmp < 0)
treep = treep->left;
else
treep = treep->right;
}
return NULL;
}
// applyinorder: inorder application of fn to treep
void applyinorder(Namevel *treep, void (*fn)(Namevel *, void *), void *arg)
{
if (treep == NULL)
return;
applyinorder(treep->left, fn, arg);
(*fn)(treep, arg);
applyinorder(treep->right, fn, arg);
}
// applypostorder: postorder application of fn to treep
void applypostorder(Namevel *treep, void (*fn)(Namevel *, void *), void *arg)
{
if (treep == NULL)
return;
applypostorder(treep->left, fn, arg);
applypostorder(treep->right, fn, arg);
(*fn)(treep, arg);
}
void printree(Namevel *treep, void *arg)
{
char *fmt = (char *)arg;
// printf("%s %x\n", treep->name, treep->value);
printf(fmt, treep->name, treep->value);
}
int main(int argc, char const *argv[])
{
Namevel *nvtree = malloc(sizeof(Namevel));
nvtree->name = "b";
nvtree->value = 1;
nvtree->left = NULL;
nvtree->right = NULL;
Namevel *nvtreeleft = malloc(sizeof(Namevel));
nvtreeleft->name = "c";
nvtreeleft->value = 2;
nvtreeleft->left = NULL;
nvtreeleft->right = NULL;
Namevel *nvtreeright = malloc(sizeof(Namevel));
nvtreeright->name = "a";
nvtreeright->value = 0;
nvtreeright->left = NULL;
nvtreeright->right = NULL;
nvtree = insert(nvtree, nvtreeleft);
nvtree = insert(nvtree, nvtreeright);
applyinorder(nvtree, printree, "%s: %x\n");
return 0;
}