aboutsummaryrefslogtreecommitdiff
path: root/6.2/tree.c
blob: 5e061a476801fb36ccb6496f3bfd060eb89dba37 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"

struct tnode *naddtree(struct tnode *p, char *w, int bar, int prevmatch)
{
	int cond;

	if (p == NULL) {
		p = talloc();
		p->word = sneed_strdup(w);
		p->count = 1;
		p->match = prevmatch;
		p->left = p->right = NULL;
	} else {
		if ((!strncmp(p->word, w, bar) && strcmp(p->word, w)))
			p->match = prevmatch = YES;

		if ((cond = strcmp(w, p->word)) == 0) {
			p->count++;
		} else if (cond < 0) {
			p->left = naddtree(p->left, w, bar, prevmatch);
		} else if (cond > 0) {
			p->right = naddtree(p->right, w, bar, prevmatch);
		}
	}

	return p;
}

void ntreeprint(struct tnode *p)
{
	if (p != NULL) {
		ntreeprint(p->left);
		if (p->match)
			printf("%4d %s\n", p->count, p->word);
		ntreeprint(p->right);
	}
}

void treefree(struct tnode *p) {
	if (p != NULL) {
		if (p->left != NULL)
			treefree(p->left);
		if (p->right != NULL)
			treefree(p->right);
		free(p->word);
		free(p);
	}
}

struct tnode *talloc(void)
{
	return (struct tnode *) malloc(sizeof(struct tnode));
}

char *sneed_strdup(char *s)
{
	char *p;

	p = (char *) malloc(strlen(s) + 1);
	if (p != NULL)
		strcpy(p, s);

	return p;
}