【发布时间】:2012-07-20 02:29:10
【问题描述】:
void BST::insert(string word)
{
insert(buildWord(word),root);
}
//Above is the gateway insertion function that calls the function below
//in order to build the Node, then passes the Node into the insert function
//below that
Node* BST::buildWord(string word)
{
Node* newWord = new Node;
newWord->left = NULL;
newWord->right = NULL;
newWord->word = normalizeString(word);
return newWord;
}
//The normalizeString() returns a lowercase string, no problems there
void BST::insert(Node* newWord,Node* wordPntr)
{
if(wordPntr == NULL)
{
cout << "wordPntr is NULL" << endl;
wordPntr = newWord;
cout << wordPntr->word << endl;
}
else if(newWord->word.compare(wordPntr->word) < 0)
{
cout << "word alphabetized before" << endl;
insert(newWord,wordPntr->left);
}
else if(newWord->word.compare(wordPntr->word) > 0)
{
cout << "word alphabetized after" << endl;
insert(newWord, wordPntr->right);
}
else
{
delete newWord;
}
}
所以我的问题是这样的:我在外部调用网关 insert()(数据流入也没有问题),每次它告诉我根或初始 Node* 为 NULL。但这应该只是在第一次插入之前的情况。每次调用该函数时,它都会将 newWord 粘贴在根部。 澄清一下:这些函数是 BST 类的一部分,root 是 Node* 和 BST.h 的私有成员
这可能很明显,我只是盯着太久了。任何帮助,将不胜感激。 此外,这是一个学校分配的项目。
最好的
【问题讨论】:
-
你是如何初始化根节点的?
-
根节点在构造函数中初始化为NULL:
-
BST::BST() {chooseRight = true;根=空; }
-
除了 NULL 之外,root 是否指向过任何东西?
-
唯一指向 NULL 的情况是构造函数通过 BST 类的实例化被隐式调用,这种情况只发生一次。 @杰克拉德克利夫
标签: c++ recursion binary-search-tree