2012-04-18 157 views
3

也許之前要求百萬次,但我根本不明白這是什麼問題。我不想在互聯網上使用任何代碼,所以我只是試圖對我的想法進行編程。這個或我的打印功能都是錯誤的。下面的代碼有什麼問題嗎?二進制搜索樹插入C++

void addNode(int value) 
    { 
     Node* newNode=new Node; 
     newNode->data=value; 
     if(root==NULL) 
      root=newNode; 
     else { 
      Node* temp=root,*parent; 
      while(temp!=NULL) 
      { 
       parent=temp; 
       if(temp->data == value) 
        return; 
       else if(temp->data < value) 
        temp=temp->left; 
       else 
        temp=temp->right; 
      } 
      temp=newNode; 
     } 
    } 
+0

您從不指定任何節點的「left」或「right」成員。 – 2012-04-18 18:21:45

+0

我正在使用'temp = temp-> left'和'temp = temp-> right'。這不算什麼? – Ali 2012-04-18 18:22:36

+0

@rolandbishop:不;這會將您的本地變量更改爲引用不同的節點,但是一旦找到插入點,您就不會修改樹。 – 2012-04-18 18:25:52

回答

6
temp=newNode; 

這將指針分配給本地變量,當函數返回時,失去了新的節點,其被丟棄。相反,您想將其分配給樹中的指針;也許是這樣的:

if (temp->data < value) {  // If the new node should be to the left 
    if (temp->left) {   // If there is a left subtree 
     temp = temp->left;  //  Move into the left subtree 
    } else {      // Otherwise 
     temp->left = newNode; //  Insert the new node there 
     return;     //  Done. 
    } 
} 

,同樣也temp->right如果value < temp->data

另外:

if (temp->data == value) 
    return; 

你有內存泄漏存在;返回前您應該delete newNode

+0

我認爲他也錯過了插入樹中間的情況。 – 2012-04-18 18:25:27

+0

謝謝你的答案。我想我有點困惑,所以這可能會變得愚蠢,但我沒有完全理解你檢查temp-> left的原因,如'if(temp-> left'。不是while循環已經規定,如果爲NULL值,我的意思是爲什麼你必須用if語句來檢查它? – Ali 2012-04-18 18:27:15

+0

@JohnKalberer:平衡樹是一種優化;更好的是讓基礎知識工作得更好 – 2012-04-18 18:28:02