From e8a9558a65ae43d3fdeecdebe59d4a1c66640435 Mon Sep 17 00:00:00 2001 From: Kyle K Date: Mon, 29 Nov 2010 01:38:18 -0600 Subject: Initial commit --- Makefile | 21 +++++++++++++++++++++ trees.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ trees.h | 22 ++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 Makefile create mode 100644 trees.c create mode 100644 trees.h diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c6cd713 --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +PROG = trees +OBJS = $(PROG).o +CC = gcc +DBGFLAGS = -g -O0 +ifdef DEBUG + CFLAGS = $(DBGFLAGS) -Wall -std=c99 +else + CFLAGS = -Wall -std=c99 -O2 -march=native -mtune=native +endif +LDFLAGS = -lm + +$(PROG): $(OBJS) + $(CC) $(LDFLAGS) $(OBJS) -o $(PROG) + +$(PROG).o: $(PROG).c trees.h + $(CC) -c $(CFLAGS) $(PROG).c + +.PHONY: clean + +clean: + rm -f *.o ./$(PROG) diff --git a/trees.c b/trees.c new file mode 100644 index 0000000..3a5599c --- /dev/null +++ b/trees.c @@ -0,0 +1,58 @@ +/* trees.c + * + * Trees + * + */ + +#include "trees.h" + +/* addtree, adds a node containing token, at or below p */ +struct tnode *bintree_insert(struct tnode *p, char *t) +{ + int cond; + + if (p == NULL) + { + p = (struct tnode *) malloc(sizeof(struct tnode)); + p->text = t; + p->count = 1; + p->left = p->right = NULL; + } + else if ((cond = strcmp(t, p->text)) == 0) + p->count++; + else if (cond < 0) /* go the the left subtree */ + p->left = bintree_insert(p->left, t); + else + p->right = bintree_insert(p->right, t); + + return p; +} + +/* in-order tree print */ +void treeprint_inorder(struct tnode *p) +{ + if (p != NULL) + { + treeprint_inorder(p->left); + printf("%4d %s\n", p->count, p->text); + treeprint_inorder(p->right); + } +} + +int main(int argc, char **argv) +{ + struct tnode *root = NULL; + + char *tokens[] = { "Anything", "that", "can", "go", "wrong", "will", + "binary", "tress", "are", "usefull", + "dreaming", "in", "digital", "living", "in", + "binary", "talking", "in", "ip"}; + int i; + for (i = 0; i < sizeof(tokens) / sizeof(char *); i++) + root = bintree_insert(root, tokens[i]); + + treeprint_inorder(root); + + return 0; +} + diff --git a/trees.h b/trees.h new file mode 100644 index 0000000..93f63d9 --- /dev/null +++ b/trees.h @@ -0,0 +1,22 @@ +#ifndef _TREES_H_ +#define _TREES_H_ + +#include +#include +#include + +struct tnode +{ + char *text; + + int count; + struct tnode *left; + struct tnode *right; +}; + +/* function prototypes */ +struct tnode *bintree_insert(struct tnode *, char *); +void treeprint_inorder(struct tnode *); + +#endif + -- cgit v1.2.3