wangzishan wangzishan - 1 month ago 6
C++ Question

why must I "new Node()" before using root in this class?

struct Node{
Node* ch[26];
string str;
Node(){
for(int i = 0; i < 26; i++) {
ch[i] = NULL;
}
str = "";
}
};
class Solution {
public:
vector<string> results;
Node* root;
void insert(Node* p, string s) {
int len = s.size();
for(int i = 0; i < len; i ++) {
if(p->ch[s[i] - 'a'] == NULL) {
p->ch[s[i] - 'a'] = new Node();
}
p = p->ch[s[i] - 'a'];
}
p->str = s;
}
vector<string> wordSearchII(vector<vector<char> > &board, vector<string> &words) {}
}


This is the Trie I defined for my problem. The "root" and "vector result" are both member variables of Solution. The question I want to ask is that why I must "new Node()" before I use root. I do not need to "new vector" before I use results. I understand that the Solution will call default constructor and then "results" will call its default constructor. Why couldn't root use the default constructor of Node?

I happen to realize that my confuse may relate to "pointer". But I still don't understand the details. Can anyone explain about it? I really appreciate it.

Answer

root is just a pointer, but you are not assigning anything for it to point at. You need to allocate a new Node object and then assign the address of that object to root, eg:

class Solution {
public:
    vector<string> results;
    Node* root;

    Solution() {
        root = new Node;
    }

    ~Solution() {
        delete root;
    }

    ...
};

Otherwise, don't make root be a pointer at all:

class Solution {
public:
    vector<string> results;
    Node root;

    ...
};

On a side note, your Node class needs a destructor to destroy any child nodes that are added to it:

struct Node{
    Node* ch[26];
    string str;

    Node(){
        for(int i = 0; i < 26; i++) {
            ch[i] = NULL;
        }
    }

    ~Node(){
        for(int i = 0; i < 26; i++) {
            delete ch[i];
        }
    }
};
Comments