You are on page 1of 5

TRIE PROGRAM: #include <iostream.h> #include <ctype.h> #include<conio.

h> class trie { private: struct node { char character; int eow; int prefixes; node* edge[26]; }*root; void preorder_display(node *); void truncate_node(node *); void delete_node(node *); public: trie(); ~trie(); // constructor // destructor

// character of the node // indicates a complete word // indicates how many words have the prefix // references to all possible sons // trie root node // preorder display // Deletes node and sub-nodes // Deletes node if prefixes is 1

void insert_word(char *); // to insert a word void delete_word(char *); // to delete a word int search_word(char *); // to search a word void display(); }; trie::trie() { root = new node(); root->character = '\0'; root->prefixes = 0; root->eow = 0; for(int i=0;i<26;i++) { root->edge[i] = NULL; } } trie::~trie() // display complete trie

{ truncate_node(root); } void trie::truncate_node(node* n) { for(int i=0;i<26;i++) { if(n->edge[i] != NULL) { truncate_node(n->edge[i]); } } delete n; } void trie::insert_word(char* s) { node *t = root; while(*s != '\0') { int c = toupper(*s) - 'A'; if(t->edge[c] == NULL) { node* n = new node(); n->character = *s; n->eow = 0; n->prefixes = 1; for(int i=0;i<26;i++) { n->edge[i] = NULL; } t->edge[c] = n; t = n; } else { t = t->edge[c]; t->prefixes++; } *s++; } t->eow = 1; } int trie::search_word(char* s)

{ node *t = root; while(*s != '\0') { int c = toupper(*s) - 'A'; if(t->edge[c] == NULL) { return 0; } else { t = t->edge[c]; } *s++; } if(t->eow == 1) return 1; else return 0; } void trie::delete_word(char* s) { node* t = root; while(*s != '\0') { int c = toupper(*s) - 'A'; if(t->edge[c] == NULL) { return; } else if(t->edge[c]->prefixes == 1) { truncate_node(t->edge[c]); t->edge[c] = NULL; return; } else { t = t->edge[c]; } *s++; } } void trie::display()

{ preorder_display(root); } void trie::preorder_display(node* t) { if(t == NULL) return; cout << "iterating :: " << t->character << " :: " << t->eow << " :: " << t->prefixes << endl; for(int i=0;i<26;i++) { if(t->edge[i] != NULL) preorder_display(t->edge[i]); } } void main() { clrscr(); trie mytrie; char *s[] = {"tree","trie","algo"};//"assoc","all","also","ass"}; for(int i=0;i<sizeof(s)/sizeof(*s);i++) { mytrie.insert_word(s[i]); } mytrie.display(); getch(); } OUTPUT: iterating :: :: 0 :: 0 iterating :: a :: 0 :: 1 iterating :: l :: 0 :: 1 iterating :: g :: 0 :: 1 iterating :: o :: 1 :: 1 iterating :: t :: 0 :: 2 iterating :: r :: 0 :: 2 iterating :: e :: 0 :: 1 iterating :: e :: 1 :: 1 iterating :: i :: 0 :: 1 iterating :: e :: 1 :: 1

You might also like