Implement Trie (Prefix Tree)

 https://leetcode.com/problems/implement-trie-prefix-tree/

class Trie {
public:
    struct Node{    
        bool isEnd = false;
        Node* children[26] = {NULL};
    };
    
    Node* root;
    Trie() {
        root = new Node();  // initialising the root
    }
    
    void insert(string word) {
        Node* curr = root;
        for(int i=0;i<word.size();i++) {
            int idx = word[i]-'a';
            if(curr->children[idx]==NULL) {
                curr->children[idx] = new Node();
            }
            curr = curr->children[idx];
        }
        curr->isEnd = true;
    }
    
    bool search(string word) {
        Node* curr = root;
        for(int i=0;i<word.size();i++) {
            int idx = word[i]-'a';
            if(curr->children[idx]==NULL) {
                return false;
            }
            curr = curr->children[idx];
        }
        if(curr->isEnd == true) {
            return true;
        } else {
            return false;
        }
    }
    
    bool startsWith(string prefix) {
         Node* curr = root;
        for(int i=0;i<prefix.size();i++) {
            int idx = prefix[i]-'a';
            if(curr->children[idx]==NULL) {
                return false;
            }
            curr = curr->children[idx];
        }
        if(curr->isEnd == true) {   //check if given prefix is itself the word
            return true;
        }
        for(int i=0;i<26;i++) {
            if(curr->children[i]) {
                return true;
            }
        }
        return false;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!