2012-05-01 68 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; 
    } 
}