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

时间:2012-07-20 02:29:11

标签: c++ recursion 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()(也没有数据流入的问题),每次它告诉我root或初始Node *为NULL。但这应该只是在第一次插入之前的情况。每次调用该函数时,它都会将newWord固定在根目录下。 澄清:这些函数是BST类的一部分,root是Node *和BST.h的私有成员

这可能很明显,而且我一直盯着太长时间。任何帮助,将不胜感激。 此外,这是一个学校指定的项目。

最佳

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

与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
        // ...
    }
    
  3. 为了帮助您更好地理解这一点,我建议您阅读有关变量范围和生命周期的更多信息。

相关问题