Why runtime error occurs?


  • 0
    O
    class TrieNode {
    public:
        // Initialize your data structure here.
        char val;
        map<char,TrieNode*> children;
        TrieNode() {
            val='0';
        }
        TrieNode(char c) {
            val=c;
        }
        ~TrieNode(){
            for(map<char, TrieNode*>::iterator iter=children.begin();iter!=children.end();++iter) delete iter->second;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
        ~Trie(){
            delete root;
        }
        // Inserts a word into the trie.
        void insert(string s) {
            TrieNode *rt=root;
            for(int i=0;i<s.size();i++){
                if(rt->children.count(s[i])==0){
                    rt->children[s[i]]=new TrieNode(s[i]);    
                }
                rt=rt->children[s[i]];
            }
            if(rt->children.count('0')==0)
                rt->children['0']=new TrieNode['0'];
        }
    
        // Returns if the word is in the trie.
        bool search(string key) {
            TrieNode *rt=root;
            for(int i=0;i<key.size();i++){
                if(rt->children.count(key[i])==0) return false;
                rt=rt->children[key[i]];
            }
            if(rt->children.count('0')>0) return true;
            else return false;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            TrieNode *rt=root;
            for(int i=0;i<prefix.size();i++){
                if(rt->children.count(prefix[i])==0) return false;
                rt=rt->children[prefix[i]];
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };

  • 0
    D

    If you look at your code carefully, you can see that there is one line:

    rt->children['0']=new TrieNode['0'];
    

    This won't create compile error, but when you run, it will be runtime error. When there is runtime error, leetcode might give you the incomplete reason why it fails (such as: Last executed input:
    insert("a"),search("a"),startsWith("a") ), although the error happen in insert function.

    Just change that line to:

    rt->children['0']=new TrieNode();
    

    There it goes! you got an accepted solution!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.