1. class Trie {
    2. public:
    3. struct Node{
    4. bool is_end;
    5. Node *son[26];
    6. Node(){
    7. is_end = false;
    8. for(int i=0;i<26;i++) son[i] = NULL;
    9. }
    10. }* root;
    11. /** Initialize your data structure here. */
    12. Trie() {
    13. root = new Node();
    14. }
    15. /** Inserts a word into the trie. */
    16. void insert(string word) {
    17. Node*p = root;
    18. for(auto c:word){
    19. int v = c-'a';
    20. if(p->son[v]==NULL) p->son[v] = new Node();
    21. p = p->son[v];
    22. }
    23. p->is_end= true;
    24. }
    25. /** Returns if the word is in the trie. */
    26. bool search(string word) {
    27. Node*p = root;
    28. for(auto c:word){
    29. int v = c-'a';
    30. if(p->son[v]==NULL) return false;
    31. p = p->son[v];
    32. }
    33. if(!p->is_end) return false;
    34. return true;
    35. }
    36. /** Returns if there is any word in the trie that starts with the given prefix. */
    37. bool startsWith(string prefix) {
    38. Node*p = root;
    39. for(auto c:prefix){
    40. int v = c-'a';
    41. if(p->son[v]==NULL) return false;
    42. p = p->son[v];
    43. }
    44. return true;
    45. }
    46. };
    47. /**
    48. * Your Trie object will be instantiated and called as such:
    49. * Trie* obj = new Trie();
    50. * obj->insert(word);
    51. * bool param_2 = obj->search(word);
    52. * bool param_3 = obj->startsWith(prefix);
    53. */