Need to understand what a Trie is before writing the code:-) This link has a nice solution, whose code is rewritten below.
1 classTrienode {2 Public:3 BOOLIsword;4trienode* children[ -];5 //Initialize your data structure here.6Trienode (): Isword (false) {7Memset (Children, NULL,sizeof(trienode*) * -);8 }9 };Ten One classTrie { A Public: - Trie () { -Root =NewTrienode (); the } - - //inserts a word into the trie. - voidInsertstringword) { +trienode* Run =Root; - for(CharC:word) { + if(! (Run-children[c-'a'])) ARun--Children[c-'a'] =NewTrienode (); atRun = run-children[c-'a']; - } -Run-Isword =true; - } - - //Returns If the word is in the trie. in BOOLSearchstringword) { -trienode* p =query (word); to returnP && PIsword; + } - the //Returns If there is any word in the trie * //That's starts with the given prefix. $ BOOLStartsWith (stringprefix) {Panax Notoginseng returnquery (prefix); - } the + Private: Atrienode*Root; thetrienode* Query (string&s) { +trienode* Run =Root; - for(Charc:s) { $ if(! (Run-children[c-'a']))returnNULL; $Run = run-children[c-'a']; - } - returnrun; the } - };Wuyi the //Your Trie object would be instantiated and called as such: - //Trie Trie; Wu //Trie.insert ("somestring"); - //trie.search ("key");
[Leetcode] Implement Trie (Prefix Tree)