summaryrefslogtreecommitdiff
path: root/btree-str.c
blob: c3c0ad30ca1ab23ffc4d8019662d8b35159ccd62 (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
	char *v;
	struct node *l;
	struct node *r;
};

struct node *cn(char *);
void an(struct node *, struct node *);
void pn(struct node *);
void fn(struct node *);

struct node *cn(char *s) {
	struct node *n;
	char *d;

	n = malloc(sizeof *n);
	if (!n)
		return NULL;
	d = malloc(strlen(s) + 1);
	if (!d)
		return NULL;
	strcpy(d, s);
	n->v = d;
	n->l = n->r = NULL;
	return n;
}

void an(struct node *r, struct node *n) {
	if (!r || !n)
		return;
	if (strcmp(n->v, r->v) > 0) {
		if (r->r)
			an(r->r, n);
		else
			r->r = n;
	}
	else {
		if (r->l)
			an(r->l, n);
		else
			r->l = n;
	}
	return;
}

void pn(struct node *n) {
	if (!n)
		return;
	if (n->l)
		pn(n->l);
	fprintf(stdout, "%s\n", n->v);
	if (n->r)
		pn(n->r);
	return;
}

void fn(struct node *n) {
	if (!n)
		return;
	if (n->l)
		fn(n->l);
	if (n->r)
		fn(n->r);
	free(n->v);
	free(n);
	return;
}

int main(int argc, char **argv) {
	struct node *r, *n;

	r = NULL;
	for (argv++; *argv; argv++) {
		n = cn(*argv);
		if (!n)
			break;
		if (r)
			an(r, n);
		else
			r = n;
	}

	pn(r);

	fn(r);

	exit(EXIT_SUCCESS);
}