2017-05-12 34 views
2

我已經通過使用遞歸嘗試了以下算法,但節點沒有被追加到樹中。請告訴我什麼是錯的。如何在BST中添加節點?

void search_add(struct node *t) 
{ 
    if(t==NULL) 
    { 
     t = newNode(temp->key); 
     return; 
    } 
    else if(t->key>temp->key) 
    { 
     search_add(t->right); 
    } 
    else if (t->key<temp->key) 
    { 
     search_add(t->left); 
    } 
} 

void insert(struct node *node, int key) 
{ 
    temp = newNode(key); 
    search_add(node); 
} 

int main(void) 
{ 
    root = newNode(50); 
    insert(root,30); 

    return 0; 
} 
+2

'T = newNode(TEMP->鍵);'僅改變通過的本地副本,然後將其遺忘,呼叫者的'T-> right'或'T-> left'保持'NULL '。 –

+1

在這個網站上有*數千*這個問題的重複。不幸的是,這個錯誤通常是由初學者和問題的標題/文本所做出的,因此它們很難實際發現。 't = newNode(temp-> key);''* * * * * * * * * * * *就功能而言,它是一個局部變量。所有這些最終都會導致內存泄漏。 [示例複製在這裏](https://stackoverflow.com/questions/13188313/why-is-my-bst-root-pointer-changing-for-some-unknown-reason)。 – WhozCraig

+0

歡迎來到StackOverflow。 請參考[遊覽], 學習問好問題stackoverflow.com/help/how-to-ask, 做個[mcve]。 如果您正在尋找調試代碼的幫助,請參閱https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Yunnosch

回答

0

的問題,如前所述byWeather Vave的是:

t = newNode(temp->key);只改變傳遞的本地副本, 然後將其遺忘,呼叫者的t->rightt->left 保持爲空。

的溶液可以是可以改變:

void search_add(struct node *t) 

這樣:

void search_add(struct node *t) 

當然,然後使用*t函數的體內,而不是t

這樣你就傳遞了一個雙指針,這將使得這個改變在函數的作用域之外可見。

0

你沒有在你的遞歸分配任何值。請嘗試下面的代碼我是一個Java所以請忽略任何語法問題。

/* If the tree is empty, return a new node */ 
    if (node == NULL) return newNode(key); 

    /* Otherwise, recur down the tree */ 
    if (key < node->key) 
     node->left = insert(node->left, key); 
    else if (key > node->key) 
     node->right = insert(node->right, key); 

    /* return the (unchanged) node pointer */ 
    return node;