Getting Started with the dictionary tree, including build, insert, and find
My algorithm knowledge is too bad, need to improve, see more practice
Description: Create a thesaurus, enter a number of words, enter the end of 0
Can query the word, return the number of times he appears in the Thesaurus, (PS: also appears once as a prefix for a word)
/*originally thought that the dictionary tree is very difficult, the result looked after the feeling foundation still is quite simple the following algorithm calculates to establish a dictionary tree, the input is 0 to end the input to query the word, returns the word which appears in the dictionary tree the frequency*/#include<stdio.h>#defineMAX 26//number of letters in English//the data type of the node that defines the dictionary treetypedefstructtrienode{intncount;//storage node prefix occurrences structTrienode *next[max];//subsequent nodes of the node}trienode;//to define an array of storage nodesTrienode memory[1000000];//defines an array of storage dictionary tree nodesintALLOCP =0;//can see the use of the subscript for a few nodes, when creating a node with//Create a dictionary treeTrienode *Creattrie () {Trienode*tmp = &Memory[allocp++];//TMP is a pointer to the root of the treeTmp->ncount =1; for(inti =0; I < -; i++) TMP->next[i] = NULL;//the root of the tree is empty after each node creation returntmp//returns the root of the number established, and changes the tree whose subtree the root is, and the member to whom the return value is assigned}//inserting a string in the dictionary treevoidInserttrietree (Trienode **root,Char*str) {Trienode*tmp = *Root; inti =0, K; while(Str[i]) {k= Str[i]-'a';//0-25 representing 26 letters of English respectively if(Tmp->next[k])//if one of the letters in the word appears in the corresponding position,{//then the number of prefixes in the corresponding position will be added 1tmp->next[k]->ncount++; } Else//If the word does not appear in the corresponding position, add the node to the corresponding position in the tree{tmp->NEXT[K] =Creattrie (); } I++; TMP= tmp->Next[k]; }}//queries A string that returns the number of occurrences of a string in a dictionaryintSearchtrietree (Trienode **root,Char*str) {Trienode*tmp = *Root; inti =0, K; while(Str[i]) {k= Str[i]-'a'; if(tmp->next[k]) tmp= tmp->Next[k]; Else return 0; I++; } returnTmp->Ncount;z}intMain () {Chars[ One]; Trienode*root =Creattrie (); while(Gets (s) && s[0] !='0') {Inserttrietree (&root, s); } while(gets (s)) {printf ("%d\n", Searchtrietree (&root, s)); } return 0;}
Getting Started with the dictionary tree