Binary+Tree,+Example+beginning+C+code


 * 1) include 
 * 2) include 

struct node { char *word; struct node *left, *right; };

struct node *tree;

showTree(struct node *aTree) { if (aTree == NULL) return; printf(" @%i: %s /%i\t\t\\%i\n", aTree, aTree->word, aTree->left, aTree->right); showTree(aTree->left); showTree(aTree->right); }

struct node *nodeWith(char *aWord) { struct node *node; node = malloc(sizeof(struct node)); node->word = aWord; return (node); }

// Pretty much as Rubin started it on the board and others refined struct node *findOrInsert(struct node *aTree, char *aWord) { int cmp; printf("findOrInsert(...%s\n", aWord); if ((cmp = strcmp(aWord, aTree->word)) == 0) return(aTree); if (cmp < 0) { if (aTree->left) return (findOrInsert(aTree->left, aWord)); aTree->left = nodeWith(aWord); return (aTree->left); } else { if (aTree->right) return (findOrInsert(aTree->right, aWord)); aTree->right = nodeWith(aWord); return (aTree->right); } }

main { struct node *tmp, *tmp2; tree = malloc(sizeof(struct node)); tree->word = "root"; showTree(tree); findOrInsert(tree, "leave"); showTree(tree); findOrInsert(tree, "house"); showTree(tree); findOrInsert(tree, "mouse"); showTree(tree); findOrInsert(tree, "house"); showTree(tree); }