#include #include #include #define WORD_LENGTH 30 typedef struct tree_node { char *word; struct tree_node *left, *right; } TreeNode; void insert(TreeNode **root, char word[]); TreeNode * searchNode(TreeNode *rt, char key[]); void printTree(TreeNode *rt, int level); void printInOrder(TreeNode *rt); void printPreOrder(TreeNode *rt); int main(int argc, char *argv[]) { TreeNode *root = NULL; /* don't forget to initially NULL this ptr! */ TreeNode *ptr; int count; char target[WORD_LENGTH]; for (count = 1; count < argc; count++) insert(&root, argv[count]); printf("\nInorder traversal of tree:\n"); printInOrder(root); printf("\nPreorder traversal of tree:\n"); printPreOrder(root); printTree(root, -1); printf("Enter a word to search for ['q' to quit]: "); scanf("%s", target); while (target[0] != 'q') { if ((ptr = searchNode(root, target)) != NULL) printf(" %s found in tree!\n", ptr->word); else printf(" %s not found in tree!\n", target); printf("\nAnother word to search for ['q' to quit]: "); scanf("%s", target); } return 0; } void insert(TreeNode **root, char word[]) { if (*root == NULL) { *root = (TreeNode *)malloc(sizeof(TreeNode)); (*root)->word = (char *)malloc(strlen(word)+1); strcpy((*root)->word, word); (*root)->left = (*root)->right = NULL; } else if (strcmp(word,(*root)->word) < 0) insert(&(*root)->left, word); else insert(&(*root)->right, word); } TreeNode * searchNode(TreeNode *rt, char key[]) { while (rt != NULL && strcmp(key, rt->word) != 0) { if (strcmp(key,rt->word) < 0) rt = rt->left; else rt = rt->right; } return rt; } void printInOrder(TreeNode *rt) { if (rt != NULL) { printInOrder(rt->left); printf("%s\n",rt->word); printInOrder(rt->right); } } void printPreOrder(TreeNode *rt) { if (rt != NULL) { printf("%s\n",rt->word); printPreOrder(rt->left); printPreOrder(rt->right); } } void printTree(TreeNode *rt, int level) { int i; if (rt != NULL) { level++; printTree(rt->right, level); for(i = 0; i < level; i++) printf(" "); printf("%s\n", rt->word); printTree(rt->left, level); } }