簡體   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