• + 0 comments
    I implemented my code using Trie with array of size 26 but only 2 test cases are passed. Can anyone help?
    
    class TrieNode{
    public:
    char data;
    TrieNode **children;
    bool isTerminal;
    
    TrieNode(char data){
        this->data = data;
        children = new TrieNode*[26];
    
        for(int i = 0; i < 26; i++){
            children[i] = NULL;
        }
    
        isTerminal = false;
    }
    

    };

    class Trie{ TrieNode *root;

    public:
    Trie(){
        root = new TrieNode('\0');
    }
    
    void add(TrieNode *root, string word){
        if(word.size() == 0){
            root->isTerminal = true;
            return;
        }
    
        int index = word[0] - 'a';
        TrieNode *child;
    
        if(root->children[index] != NULL){
            child = root->children[index];
        }
        else{
            child = new TrieNode(word[0]);
            root->children[index] = child;
            // cout<<root->children[index]->data<<endl;
        }
    
        add(child, word.substr(1));
    }
    
    void add(string word){
        add(root, word);
    }
    
    int find(TrieNode *root, string word){
    
        if(word.size() == 0){
            int counter = 1;
    
            for(int i = 0; i < 26; i++){
                if(root->children[i] != NULL){
                    counter++;
                }
            }
            return counter;
        }
    
        int index = word[0] - 'a';
    
        if(root->children[index] != NULL){
            TrieNode *child = root->children[index];
            return find(child, word.substr(1));
        }
        else{
            return 0;
        }
    
    }
    
    int find(string word){
        return find(root, word);
    }
    

    };

    vector contacts(vector> queries) { vector result; Trie *trie = new Trie();

    for (int i=0; i < queries.size(); i++) {
    
        if (queries[i][0] == "add") {
            trie->add(queries[i][1]);
        }
        else if(queries[i][0] == "find") {
            result.push_back(trie->find(queries[i][1]));
        }
    }
    
    return result;
    

    }