Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Implement the dictionary tree, there is nothing to say.
1 classTrienode {2 Public:3 //Initialize your data structure here.4Trienode *ch[ -];5 BOOLIsKey;6Trienode (): IsKey (false) {7 for(Auto &a:ch) A =NULL;8 }9 };Ten One classTrie { A Public: - Trie () { -Root =NewTrienode (); the } - - //inserts a word into the trie. - voidInsertstrings) { +Trienode *p =Root; - for(Auto &a:s) { + inti = A-'a'; A if(P->ch[i] = = NULL) P->ch[i] =NewTrienode (); atp = p->Ch[i]; - } -P->iskey =true; - } - - //Returns If the word is in the trie. in BOOLSearchstringkey) { -Trienode *p =Root; to for(Auto &A:key) { + inti = A-'a'; - if(P->ch[i] = = NULL)return false; thep = p->Ch[i]; * } $ returnP->IsKey;Panax Notoginseng } - the //Returns If there is any word in the trie + //That's starts with the given prefix. A BOOLStartsWith (stringprefix) { theTrienode *p =Root; + for(Auto &A:prefix) { - inti = A-'a'; $ if(P->ch[i] = = NULL)return false; $p = p->Ch[i]; - } - return true; the } - Wuyi Private: thetrienode*Root; - }; Wu - //Your Trie object would be instantiated and called as such: About //Trie Trie; $ //Trie.insert ("somestring"); - //trie.search ("key");
[Leetcode] Implement Trie (Prefix Tree)