2013-02-17 65 views
-1

我知道這可能看起來很簡單,但我一直在摸索着我的頭幾個小時,試圖弄清楚爲什麼我會這樣做,thisNode總是NULL。因爲這是空的,這意味着沒有任何事情最終會被添加到樹中。有沒有任何想法? Arghhh二進制搜索樹節點總是NULL

struct node *tra(struct node * start, Type input) 
{ 
    struct node * thisNode = start; 

    if (thisNode == NULL) 
     return thisNode; 
    else 
    { 
     Type current = thisNode -> el; 

     if (strcmp(input, current) > 0) 
      return tra(thisNode -> right, input); 
     else if (strcmp(input, current) < 0) 
      return tra(thisNode -> left, input); 
     else 
     return thisNode; 
    } 
} 

Ta insert(Type input, Ta ta) 
{ 
    if ((find(input, ta)) == FALSE) 
    { 
     struct node *newEl = tra(ta -> head, input); 
     newEl = (struct node*)malloc(sizeof(struct node)); 
     newEl -> el = input; 
     newEl -> left = NULL; 
     newEl -> right = NULL; 
    } 

    return ta; 
} 

Boolean find(Type input, Ta ta) 
{ 
    if (tra(ta -> head, input) == NULL) 
     return FALSE; 
    else 
     return TRUE; 
} 
+2

要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或添加打印語句)來隔離問題,然後構造一個[最小測試用例](http://sscce.org)。 – 2013-02-17 22:43:24

+0

@OliCharlesworth抱歉,我應該改寫這個問題。我的意思是你有什麼想法,我可以改正這一點?在過去的幾個小時裏,我一直在使用一個調試器來解決這個問題。我知道它是NULL,因爲它總是進入第一個if語句,但我根本無法弄清楚爲什麼會出現這種情況。 – user1899174 2013-02-17 22:49:27

+0

http://stackoverflow.com/q/14926949/905902是否有任何理由重新發布相同的問題? – wildplasser 2013-02-17 23:12:14

回答

1

這裏的問題是:你分配的新節點

 struct node *newEl = tra(ta -> head, input); 
     newEl = (struct node*)malloc(sizeof(struct node)); 

,但隨後的指針墩迷路。你的函數tra應該返回一個指向指針的指針,讓插入函數修改你附加新創建節點的節點。

0

的問題如下:

當有沒有在BST,這觸發tra

if (thisNode == NULL) 
    return thisNode; 

所以在insert然後newEl == NULL

然後你malloc分配指針newEl一個新的值指向分配的內存。但是您返回的原始指針仍具有值NULL(因爲給指針的一個新值的副本不會更改原始指針)。處理這種

選項:

  • 返回一個指針的指針(struct node **)(我想你想也需要一個指針作爲參數傳遞給一個指針insert功能)。
  • 更改您的支票tra查看下一個元素(以及相應的更改)。對於鏈接列表,它看起來像:if (thisNode->next == NULL) return thisNode;insert你可以使用newEl->next。儘管對於鏈接列表通常是一個很好的選項,但對於BST來說這是一個更多的努力,因爲您需要返回左側或右側節點是NULL,還是在insert中再次執行此檢查。
    • 請注意 - 您必須使用newEl->leftnewEl->right,insert
  • 返回參考 - 這可能是最簡單的選擇。更改tra返回struct node *&並更改newEl聲明struct node *&newEl = ...,這可能是所有。
+0

好,所以我決定去第二個選項。但是,如果我將檢查改爲'if(thisNode - > head == NULL)',當然我不需要在插入時使用'newEl - > head'做任何更改,因爲我已經返回'newEl - >頭''在'tra'? – user1899174 2013-02-17 22:59:51

+0

另外,爲什麼我需要檢查'thisNode'是否有'head'元素?當然'樹'會有一個頭元素? – user1899174 2013-02-17 23:05:42

+0

@ user1899174請參閱編輯。 – Dukeling 2013-02-17 23:11:41