【问题标题】:Insertion error in Binary Search tree二叉搜索树中的插入错误
【发布时间】: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


【解决方案1】:

就像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
        // ...
    }
    

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

【讨论】:

    【解决方案2】:

    分配wordPntr = newWord;insert 函数的本地函数,在这种情况下它应该以某种方式设置树的根。

    【讨论】:

    • 但是 root 是一个 Node* 并且是 BST 类的私有成员,并且 newWord 是一个动态分配的内存位置,所以即使在函数完成之后,root 也应该指向 newWord。
    猜你喜欢
    • 2016-12-04
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多