Trie (tire)

First, what is the tree?

Here Insert Picture Description
Such? , It is also a tree, but the tree is the real life of nothing, as long as the learned programming all know, the computer world where there are trees, trees in the computer like this

Here Insert Picture Description
Like so much like tree roots is not to say, because I can see it is down to the extension application from the tree uses in the computer is also very wide, what sort ah, ah look, indexing, of course ...... Find Search still the most used.
Take a look at the official definition of a tree:
the tree is a root and a number of sub-tree consisting of stars. Tree is constituted by a set and a relationship defined in the set. Elements of the collection called tree nodes, parent-child relationship definition is called relationship. Parent-child relationship between the nodes of the tree establishes a hierarchy. There is a node having a special position in this hierarchy, this node is called the root node of the tree, otherwise known as root.

Second, the realization of a simple tree

  • A tree is not simple to achieve, first parse tree structure, nothing more than a tree node, he played the following sub-tree and there are a lot attached to it, put it so around, look at the chart will understand:

Here Insert Picture Description
Each color can separate out a tree to do right, even if it is only one node can become a tree, it is not that breach. There are multiple trees in the tree, then you can define a structure:

typedef struct TreeNode{
	struct TreeNode* children[INFINITE]; 
}*Tree;

A simple tree came, of course, infinite here is serious business, the most important thing is to understand the concept. In memory of them is how this tree has a look like, see below:
Here Insert Picture Description
These small squares which also represents the memory space in your computer, you can see is a memory space to store a tree, so to speak .
There are many types of trees, above which is the most common tree, and even he was not even a space for data storage are not, there is a tree is the most common, and that is a binary tree, binary tree of inherited characteristics, but they have Some of the more unique value. Binary tree, listening to the name, it comes with a two, what is the meaning of the two is it, that is, the next binary tree node allows up to two nodes, his structure is this:
Here Insert Picture Description
to see it this structure, we can immediately it defines knew it even simpler than the tree, its child tree volume has been limited, at best, only two, the left seems to be nothing more than a child, the right of a child. Then you can define its structure of:

typedef struct BinaryTreeNode{
	DataType data;
	struct BinaryTreeNode* leftChild;
	struct BinaryTreeNode* rightChild;
}*BinaryTree;

You can see in the code, we defined two children in addition to the nodes, but also more define a space for storing data, since we use a tree structure that must be brought to meet their own needs it, it can not be bring it out;
the code we looked again to see him are stored in the computer memory of them right:
Here Insert Picture Description
this should be very clear, NULL is represented by # is no point, the computer world is nothing but only two states, 0 or 1, this binary tree crashing into the arms of the right, is the extensive use of binary tree, sorting, coding, decision-making, and so on and so on are all related and binary tree, I will have time out of a binary tree of related Notes.

Today's protagonist Tire-- trie

With the groundwork in front of some trees, presumably now come to understand the concept of the dictionary tree should be much easier, trie is what is it, in fact, its structure is a common tree structure, of course, there will certainly be a little different, it It can be used to do it? We wish to see how a demand

Demand Content: Now you have a list with a word, my hands have a word, you can quickly find out whether this word exists in your list it among

Probably under a lot of partners, it would immediately think of this line of thinking, your code might look like this:

bool wordIsExisted(vector<string> wordList,string targetWord){
	for(int i=0;i<wordList.size();i++){
		if(wordList.at(i) == targetWord){
			return true	
		}
	} 
return false;
}

Here for simplicity is directly == numbers to be judged, its internal program is actually still on the character strings corresponding to the two positions are compared one by one, so here can easily count the time complexity of the above procedure of this degree in O (n2);
if a word in the word list is short, less the number of words using the above method, of course this is feasible, but if the number of words, and length are terrifyingly large, let's compare one character at a time 1s list of words still need time to count (measure of course just about here, certainly not so slow), the number of words I have a list of 10,000, the length of each word is 10000, and we're looking for in the the last one, this requires spending time is 10000 × 10000 × 1s
is 100,000,000 seconds (about 3 years to finish) this is fatal.
So smart predecessors, they come up a structure that is mentioned in the title trie
to first on the map:

Here Insert Picture Description
It is this structure where each node represents a red representatives here to exist between a root root word, not ugly every time we we're looking for the existence of the word, they are beginning to find the root node.

To say I am looking for he word, then I first pointer to the root node, its children to explore whether there has h this character, if I put a pointer to the node h, and then again below from h-node under the search for their children and whether there is a single e node, then found, we again pointer to e node, then find the word we are looking for has been swept to the end, and then finally determine whether this node is red is (whether is the word, the final output is true;
may the words were not so clear, or look at the following chart to understand faster:
Here Insert Picture Description

Here Insert Picture Description
Here Insert Picture Description
This will understand the principle, let's look at the code implementation process:

#include<iostream>

using namespace std;


typedef struct TireNode{
    char c;
    bool isWord;
    TireNode* child[26];
}*Tire;

void insertWord(Tire t,string word){
    if(t==nullptr){return;}
    for(char w: word){              
        if(t->child[w-'a']){        // 判断是否存在此字母
            t = t->child[w-'a'];    // 跳至下一个节点
        }
        else{
            Tire node = (Tire) malloc(sizeof(TireNode));
            *node = {w,false,{nullptr}};        // 写c千万别忘了初始化血的教训
            t = t -> child[w - 'a'] = node;
        }
    }
    t->isWord = true;
}

bool findWord(Tire t,string word){
    for(char w:word){
        if(t->child[w-'a']){        // 判断当前字母是否存在
            t = t->child[w-'a'];
        }
        else{
            return false;
        }
    }
    return t->isWord;
}


int main(){
    Tire t =  (Tire) malloc(sizeof(TireNode));
    *t = {'\r',false,{nullptr}};
    insertWord(t, "he");
    insertWord(t,"she");
    insertWord(t,"her");
    cout << boolalpha;
    cout << findWord(t,"his") << endl;
    cout << findWord(t,"he") << endl;
    cout << findWord(t,"her") << endl;
}

Published 27 original articles · won praise 62 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42359956/article/details/105227542