No Prefix Set

  • + 0 comments

    when you are searching through a tire tree, you should be able to detect whether the current path contains a prefix or the current string you are searching is a prefix of another string.

    // if any prefix existing on this path
    bool checkPrefix(string& word, TrieNode* node){
        TrieNode* current = node;
        for(char ch:word){
            ch -= 'a';
            if(!current->children[ch]) break;
            current = current->children[ch];
            if(current->isEnd) return true;
        }
        return false;
    }
    // if the current string is a prefix of other string
    bool isPrefix(string& word, TrieNode* node){
        TrieNode* current = node;
        for(char ch:word){
            ch -= 'a';
            if(!current->children[ch]) return false;
            current = current->children[ch];
        }
        
        for(auto& next:current->children){
            if(next) return true;
        }
        return false;
    }