Trie Tree:
Also known as the word search tree, Trie tree, is a tree-shaped structure, is a hash tree variant. Typical applications are used for statistics, sorting, and saving a large number of strings (but not limited to strings), so it is often used by search engine systems for text frequency statistics. Its advantages are: the use of the common prefix of the string to reduce query time, to minimize the unnecessary string comparison, query efficiency than Hashi, is a space-time method.
The dictionary tree is very similar to the dictionary, when you want to look up a word is not in the dictionary tree, first look at the first letter of the word is not in the first layer of the dictionary, if not, the dictionary tree does not have the word, if in the child node in the letter is not a second letter, there is no description of the word, Some words continue to search in the same way. The dictionary tree can be used not only to store letters, but also to store numbers and other data.
The red dots on this trie tree represent the existence of the word, which is equivalent to a marker.
See the code for specific explanations:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace std;const int MAXN = 10010;const int max_size = 26;struct trie{int ch[maxn][max_size];//CH[I][J] indicates that the child node of section J of node I is not present. int VAL[MAXN]; int sz; Total number of nodes Trie () {sz = 1; Initially only one root node memset (ch[0],0,sizeof (ch[0])); } int ID (char c) {//character C is numbered return C-' a '; } void Insert_str (char *s) {//insert string int u = 0,len = strlen (s); for (int i=0;i<len;i++) {int c = ID (s[i]); if (!ch[u][c]) {//node does not exist memset (ch[sz],0,sizeof (Ch[sz])); val[sz]=0; ch[u][c]=sz++; New node} U=ch[u][c]; } val[u]=1; Mark a string exists} bool Find_str (char *s) {//find a prefix int len = strlen (s), u=0; for (int i=0;i<len;i++) {int c=id (s[i]); if (!ch[u][c]) return false; U=CH[U][C]; } return true; If you want to determine if a string exists without the IF(Val[u])}}; int main () {Trie T; T.insert ("abc"); T.insert ("ABCD"); T.insert ("ABDD"); if (T.FIND_STR ("abc")) Puts ("Yes,abc"); Else puts ("no,abc"); if (T.find_str ("Def")) puts ("Yes,def"); Else puts ("no,def"); return 0;}
Trie Tree (Dictionary tree)