trie树

来源:互联网 发布:js shift splice 编辑:程序博客网 时间:2024/06/06 17:45

字典树,顾名思义,像字典一样的树。


从上面的图中,我们或多或少的可以发现一些好玩的特性。
      第一:根节点不包含字符,除根节点外的每一个子节点都包含一个字符。
      第二:从根节点到某一节点,路径上经过的字符连接起来,就是该节点对应的字符串。
      第三:每个单词的公共前缀作为一个字符节点保存。
Tire树一般用来词频统计和前缀匹配。

现在以211. Add and Search Word - Data structure design为例来对字母树进行举例:https://leetcode.com/problems/add-and-search-word-data-structure-design/

这个树的难点在于数据结构的设计和添加字母。所以在设计的时候一定要明白根节点不包含字符,所以添加字母的时候我们都是以node->next进行访问的,而next是个数组,每个数组代表一个字母。这个也要注意!
删除的时候需要注意递归的变量:node,string和当前判断string的第几个字符。
如果不包含 '.'的判断,那么代码非常简单,因为回溯的条件就一个——当前字符不存在。而满足的条件也很简单——字符串访问结束,且字母树的end为true
有适配符的存在,就多了一个判断,因为适配符适配任何字母,所以对当前字母树的下一个节点以此进行搜索即可。

class TrieNode{public:    bool end;    TrieNode* next[26];    TrieNode(){        memset(next,0,sizeof(next));        end=false;    }};class WordDictionary {public:    TrieNode *trRoot;    // Adds a word into the data structure.    void addWord(string word) {        if(trRoot==NULL){            trRoot=new TrieNode();        }        TrieNode* tmp=trRoot;        for(int i=0;i<word.size();i++){            if(tmp->next[word[i]-'a']==NULL){                tmp->next[word[i]-'a']=new TrieNode();            }            if(i<word.size()-1){                tmp=tmp->next[word[i]-'a'];            }            else{                tmp->next[word[i]-'a']->end=true;            }        }    }    // Returns if the word is in the data structure. A word could    // contain the dot character '.' to represent any one letter.    bool search(string word) {        if(trRoot==NULL){            trRoot=new TrieNode();        }        return dfs(trRoot,word,0);    }        bool dfs(TrieNode* node,string &word,int id){        if(id==word.size()){            if(node->end==true) return true;            else return false;        }        if ('.' == word[id]) {            for (int i = 0; i < 26; ++i) {                if (node->next[i] && dfs(node->next[i], word, id + 1)) {                    return true;                }            }            return false;        }         else{            if(node->next[word[id]-'a']==NULL) return false;            return dfs(node->next[word[id]-'a'],word,id+1);        }        return false;    }         WordDictionary() {        trRoot = NULL;    }};// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary;// wordDictionary.addWord("word");// wordDictionary.search("pattern");


0 0
原创粉丝点击