[英]Insertion error in Binary Search tree
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;
}
}
So my problem is this: I call the gateway insert() externally (also no problems with the inflow of data) and every time it tells me that the root, or the initial Node* is NULL. 所以我的问题是这样的:我在外部调用网关insert()(数据输入也没有问题),每次它告诉我根或初始Node *为NULL时。 But that should only be the case before the first insert. 但这仅在第一次插入之前是这种情况。 Each time the function is called, it sticks the newWord right at the root. 每次调用该函数时,它将newWord粘贴在根目录上。 To clarify: These functions are part of the BST class, and root is a Node* and a private member of BST.h 需要说明的是:这些函数是BST类的一部分,而root是Node *和BST.h的私有成员。
It's possible it is quite obvious, and I have just been staring too long. 可能很明显,我凝视的时间太长了。 Any help would be appreciated. 任何帮助,将不胜感激。 Also, this is a school-assigned project. 另外,这是学校分配的项目。
Best 最好
The assignment wordPntr = newWord;
赋值wordPntr = newWord;
is local to the insert
function, it should somehow set the root of the tree in this case. 对于insert
函数而言是本地的,在这种情况下,它应该以某种方式设置树的根。
Like user946850 says, the variable wordPntr
is a local variable, if you change it to point to something else it will not be reflected in the calling function. 就像user946850所说的那样,变量wordPntr
是一个局部变量,如果将其更改为指向其他变量,它将不会反映在调用函数中。
There are two ways of fixing this: 有两种解决方法:
The old C way, by using a pointer to a pointer: 旧的C方式,通过使用指向指针的指针:
void BST::insert(Node *newWord, Node **wordPntr) { // ... *wordPntr = newWord; // ... }
You call it this way: 您这样称呼它:
some_object.insert(newWord, &rootPntr);
Using C++ references: 使用C ++参考:
void BST::insert(Node *newWord, Node *&wordPntr) { // Nothing here or in the caller changes // ... }
To help you understand this better, I suggest you read more about scope and lifetime of variables. 为了帮助您更好地理解这一点,建议您阅读有关变量范围和生存期的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.