diff options
author | Kyle K <kylek389@gmail.com> | 2010-11-29 01:38:18 -0600 |
---|---|---|
committer | Kamil Kaminski <kamilkss@gmail.com> | 2010-11-29 01:38:18 -0600 |
commit | e8a9558a65ae43d3fdeecdebe59d4a1c66640435 (patch) | |
tree | 6ce50ae0188b26cd34d502878ec8ff5991192cd6 | |
download | trees-e8a9558a65ae43d3fdeecdebe59d4a1c66640435.tar.gz trees-e8a9558a65ae43d3fdeecdebe59d4a1c66640435.tar.bz2 trees-e8a9558a65ae43d3fdeecdebe59d4a1c66640435.zip |
Initial commit
-rw-r--r-- | Makefile | 21 | ||||
-rw-r--r-- | trees.c | 58 | ||||
-rw-r--r-- | trees.h | 22 |
3 files changed, 101 insertions, 0 deletions
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) @@ -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; +} + @@ -0,0 +1,22 @@ +#ifndef _TREES_H_ +#define _TREES_H_ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +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 + |