繁体   English   中英

二进制搜索树中的插入错误

[英]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;
  }
}

所以我的问题是这样的:我在外部调用网关insert()(数据输入也没有问题),每次它告诉我根或初始Node *为NULL时。 但这仅在第一次插入之前是这种情况。 每次调用该函数时,它将newWord粘贴在根目录上。 需要说明的是:这些函数是BST类的一部分,而root是Node *和BST.h的私有成员。

可能很明显,我凝视的时间太长了。 任何帮助,将不胜感激。 另外,这是学校分配的项目。

最好

赋值wordPntr = newWord; 对于insert函数而言是本地的,在这种情况下,它应该以某种方式设置树的根。

就像user946850所说的那样,变量wordPntr是一个局部变量,如果将其更改为指向其他变量,它将不会反映在调用函数中。

有两种解决方法:

  1. 旧的C方式,通过使用指向指针的指针:

     void BST::insert(Node *newWord, Node **wordPntr) { // ... *wordPntr = newWord; // ... } 

    您这样称呼它:

     some_object.insert(newWord, &rootPntr); 
  2. 使用C ++参考:

     void BST::insert(Node *newWord, Node *&wordPntr) { // Nothing here or in the caller changes // ... } 

为了帮助您更好地理解这一点,建议您阅读有关变量范围和生存期的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM