Defined
Dictionary tree, also known as the word search tree, Trie tree, is a tree structure, the typical application is used for statistics, sorting and saving a large number of strings, so often used by the search engine system for text word frequency statistics. Its advantages are: the use of the common prefix of the string to save storage space, the maximum reduction of meaningless string comparisons, query efficiency than hash table high.
Explain
This picture is more classic
Is the character that is stored at each time, and the dot marks whether the character of the previous edge is present
The existing string has ABC abcd abd ....
Code
#include <cstdio>#include <cstring>#include <algorithm>#include <string>using namespace STD;intCntstructNode {intIdintPrefix//Record prefix countNode *next[ -];//point to the next level of the dictionary tree, if all lowercase letters are 26 it depends on the situation.Node () { for(intI=0;i< -; i++) Next[i]=null; ID =0; prefix=0; }//Initialize}*root;intInsert (Char*s) {intLen =strlen(s); node *p= root; for(intI=0; i<len;i++) {intk=s[i]-' A ';if(P->next[k]==null) {p->next[k]=NewNode (); } p=p->next[k]; p->prefix++; }if(p->id==0)returnp->id=++cnt;returnp->id; }//INSERT and assign IDintFindCharS[]) {intLen =strlen(s); Node *p =root; for(intI=0; i<len;i++) {p=p->next[s[i]-' A ']; }returnp->prefix; }//Find out how many prefixes the prefix is.intX//Record the total number of strings involved in the sortintall[ $];//record the sequential IDvoidOutput (node *p) {if(P!=null) {if(p->id!=0) {all[x++]=p->id; } for(intI=0;i< -; i++) {if(P->next[i]) {output (p->next[i]); } } } }//String sortintMain () {cnt =0; Root =NewNode ();Chars[ -][ -];Chars2[ -][ -];intNscanf("%d", &n); for(intI=0; i<n;i++) {scanf('%s ', S[i]);printf("%d\n", Insert (S[i]));strcpy(S2[insert (S[i])],s[i]); } for(intI=0; i<n;i++) {printf("%d\n", find (S[i])); }/ * After sorting * /x=0; Output (root);printf("%d\n", x); for(intI=0; i<x;i++) {printf("%d%s\n", All[i],s2[all[i]]); } }
Some questions and their code stamps I
Copyright notice: All brothers, please feel free to reprint, please indicate who is the brother
A quick Insert query data structure in the dictionary tree