2012-05-01 70 views
0

刪除所有值時,所以我有這個函數運行,因爲它使返回分段錯誤的麻煩。我已經縮小到「刪除根目錄」了行,但不知道如何解決這個錯誤。分段故障在二叉搜索樹

有什麼建議嗎?

這裏是包括在分配前和後置條件:

//前提條件:根是一個指針指向一個二進制搜索 樹的根。

//後置條件:該函數刪除二叉搜索樹 並設置//根爲NULL的所有節點。

template<class Key, class Item> 
void tree_clear(bstNode<Item, Key>*& root) 
{ 
bstNode<Item, Key>* child; 
if(root != NULL) 
{ 
    child = root->left(); 
    tree_clear(child); 
    child = root->right(); 
    tree_clear(child); 
    delete root; 
    root = NULL; 
} 
} 
+0

什麼是從返回 - >左()和?如果這些函數在最深節點上不返回NULL,則可能會出現段錯誤。 – akatakritos

+0

因爲你的tree_clear需要引用,是不是調用tree_clear(NULL)是壞事? –

+0

他正在檢查NULL。我認爲這些函數在調用最深的節點時可能會返回一些隨機指針。由於該隨機指針不爲null,因此它會嘗試tree_clear並將其刪除。 – akatakritos

回答

0

你的論點是一個指針引用...我認爲這應該是一個指針的指針:

void tree_clear(bstNode<Item, Key>** root) 
+0

它仍然給我一個分段錯誤。我也不能真正改變函數原型,因爲我們的教授希望我們實現它。任何其他想法? –

+0

嘗試刪除* root; * root = NULL; ...如果你這樣做,你需要改變警惕if(* root == NULL){} – Stretch

0

那麼,如果你不能改變的簽名,嘗試

>右()非常最深的節點上 -
template<class Key, class Item> 
void tree_clear(bstNode<Item, Key>*& root) 
{ 
    bstNode<Item, Key>* child; 
    if(root != NULL) 
    { 
    if (child = root->left()) { 
     tree_clear(child); 
    } 
    if (child = root->right()) { 
     tree_clear(child); 
    } 
    delete root; 
    } 
}