I'm trying to understand this program, why do they have to make Trie* pCrawl = root
, why don't they just use the root
of the tree and insert directly to it:
void insert(struct TrieNode *root, string key)
{
struct TrieNode *pCrawl = root;
for (int i = 0; i < key.length(); i )
{
int index = key[i] - 'a';
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isEndOfWord = true;
}
CodePudding user response:
I don't think pCrawl
is needed.
The argument root
is a copy of what is passed and modifying that won't affect the caller, so it is free to modify the value of root
in the function.
It may be for clarity gained by using clear names for the argument (for input) and variable (for processing).