首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >二叉搜索树中的插入错误

二叉搜索树中的插入错误
EN

Stack Overflow用户
提问于 2012-07-20 10:29:11
回答 2查看 198关注 0票数 1
代码语言:javascript
复制
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*为空。但应该只在第一次插入之前出现这种情况。每次调用该函数时,它都会将newWord放在根目录下。需要说明的是:这些函数是BST类的一部分,root是Node*和BST.h的私有成员

这很可能是很明显的,我只是盯着看了太久。任何帮助都将不胜感激。另外,这是一个学校指定的项目。

最好的

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-20 14:48:17

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

有两种方法可以解决这个问题:

通过使用指向指针的指针,

  1. 旧的C方式:

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

你这样叫它:

&rootPntr);

  • Using参考资料(some_object.insert,newWord,newWord C++ references:

void BST::insert(节点*newWord,节点*&wordPntr) { //此处或调用方中没有任何更改// ... }

为了帮助您更好地理解这一点,我建议您阅读更多关于变量的作用域和生存期的内容。

票数 0
EN

Stack Overflow用户

发布于 2012-07-20 10:32:00

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11572041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档