Example Program To Implement Dictionary Using Binary Search Tree
Example Program To Implement Dictionary Using Binary Search Tree
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct BSTnode {
char word[128], meaning[256];
struct BSTnode *left, *right;
};
struct BSTnode *root = NULL;
struct BSTnode * createNode(char *word, char *meaning) {
struct BSTnode *newnode;
newnode = (struct BSTnode *)malloc(sizeof(struct BSTnode));
strcpy(newnode->word, word);
strcpy(newnode->meaning, meaning);
newnode->left = newnode->right = NULL;
return newnode;
}
void insert(char *word, char *meaning) {
struct BSTnode *parent = NULL, *current = NULL, *newnode = NULL;
int res = 0;
if (!root) {
root = createNode(word, meaning);
return;
}
for (current = root; current !=NULL;
current = (res > 0) ? current->right : current->left) {
res = strcasecmp(word, current->word);
if (res == 0) {
printf("Duplicate entry!!\n");
return;
}
parent = current;
}
newnode = createNode(word, meaning);
if (current == root) {
root = temp;
free(current);
return;
}
flag > 0 ? (parent->left = temp) :
(parent->right = temp);
} else {
/* delete node with two children */
struct BSTnode *successor = NULL;
while (1) {
successor = temp->left;
if (!successor->left)
break;
temp = successor;
}
temp->left = successor->right;
successor->left = current->left;
successor->right = current->right;
if (current == root) {
root = successor;
free(current);
return;
}
(flag > 0) ? (parent->left = successor) :
(parent->right = successor);
}
}
free (current);
return;
}
void findElement(char *str) {
struct BSTnode *temp = NULL;
int flag = 0, res = 0;
if (root == NULL) {
printf("Binary Search Tree is out of station!!\n");
return;
}
temp = root;
while (temp) {
case 2:
printf("Enter the word to delete:");
fgets(str, 100, stdin);
deleteNode(str);
break;
case 3:
printf("Enter the search word:");
fgets(str, 100, stdin);
findElement(str);
break;
case 4:
inorderTraversal(root);
break;
case 5:
exit(0);
default:
printf("You have entered wrong option\n");
break;
}
}
return 0;
}