Implement Trie (Prefix Tree)
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Problem Solving Ideas:
The prefix tree. Since the value is set to A-Z, we can assume that it is a 26-fork tree. Note that each node also needs to include a tag that indicates whether the sequence of paths from the root to the node is a word.
Class Trienode {public://Initialize your data structure here. Trienode () {this->bword=false; for (int i=0; i<26; i++) {this->son[i] = NULL; }} trienode* Getson (char c) {return this->son[c-' a ']; } void Setson (int i, trienode* node) {This->son[i] = node; } bool Isword () {return this->bword; } void Markasword () {This->bword = true; }private:bool Bword; trienode* son[26];}; Class Trie {Public:trie () {root = new Trienode (); }//Inserts a word into the trie. void Insert (string s) {int len = s.length (); trienode* parent = root, *node; for (int i=0;i<len; i++) {node = Parent->getson (S[i]); if (node = = NULL) {node=new trienode (); Parent->setson (S[i]-' a ', node); } parent = node; } parent->markasword (); }//RetuRNs If the word is in the trie. BOOL Search (string key) {int len = key.length (); trienode* node = root; for (int i=0; i<len; i++) {node = Node->getson (Key[i]); if (Node==null) {return false; }} return Node->isword (); }//Returns If there is any word in the trie//that starts with the given prefix. BOOL StartsWith (string prefix) {int len = prefix.length (); trienode* node = root; for (int i=0; i<len; i++) {node = Node->getson (Prefix[i]); if (Node==null) {return false; }} return true; }private:trienode* root;};/ /Your Trie object would be instantiated and called as such://Trie trie;//trie.insert ("somestring");//Trie.search ("key") ;
[Leetcode] Implement Trie (Prefix Tree)