00001 #include <stdio.h>
00002 #include <stdlib.h>
00003
00004
00005 #include "MALLOC.h"
00006
00007 #include "bt-int.h"
00008
00009
00010 int BTI_init( struct bti_node **n )
00011 {
00012 *n = NULL;
00013
00014 return 0;
00015 }
00016
00017 int BTI_add( struct bti_node **n, int value )
00018 {
00019 int collision = 0;
00020 int dir = 0;
00021 struct bti_node *p = NULL, *node = *n;
00022
00023
00024 while (node != NULL)
00025 {
00026 if (value > node->data) { p = node; dir=1; node = node->r; }
00027 else if (value < node->data) { p = node; dir=-1; node = node->l; }
00028 else if (value == node->data)
00029 {
00030 collision = 1;
00031 break;
00032 }
00033 }
00034
00035 if (collision == 0)
00036 {
00037 struct bti_node *leaf;
00038
00039 leaf = MALLOC(sizeof(struct bti_node));
00040 if (leaf == NULL)
00041 {
00042 return -1;
00043 }
00044
00045 leaf->data = value;
00046 leaf->l = leaf->r = NULL;
00047
00048 if (p != NULL)
00049 {
00050 switch (dir) {
00051 case 1:
00052 p->r = leaf;
00053 break;
00054 case -1:
00055 p->l = leaf;
00056 break;
00057 }
00058 } else {
00059 *n = leaf;
00060 }
00061
00062
00063 }
00064
00065 return collision;
00066 }
00067
00068
00069 int BTI_dump( struct bti_node **n )
00070 {
00071 struct bti_node *node;
00072
00073 node = *n;
00074
00075 if (node->l) BTI_dump(&(node->l));
00076 if (*n) { fprintf(stdout,"%d, ", node->data); }
00077 if (node->r) BTI_dump(&(node->r));
00078
00079 return 0;
00080
00081 }
00082
00083 int BTI_done( struct bti_node **n )
00084 {
00085 struct bti_node *node;
00086
00087 if (n == NULL) return 0;
00088 if (*n == NULL) return 0;
00089
00090 node = *n;
00091
00092 if (node->l) BTI_done(&(node->l));
00093 if (node->r) BTI_done(&(node->r));
00094 if (*n) { FREE(*n); *n = NULL; }
00095
00096 return 0;
00097 }
00098