Sim*_*ley 7 c c++ recursion binary-tree binary-search-tree
我试图理解删除二叉搜索树的递归方法是如何工作的.我在许多地方遇到的代码如下所示:
void destroy_tree(struct node *leaf)
{
if( leaf != 0 )
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
free( leaf );
}
}
Run Code Online (Sandbox Code Playgroud)
我无法理解a)如果例程中没有返回,它是如何工作的?b)当free()被调用时?我想想,例如,这样一棵树:
10
/ \
6 14
/ \ / \
5 8 11 18
Run Code Online (Sandbox Code Playgroud)
所以我的理解是我遍历10-> 6-> 5,然后我调用destroy_tree(5->左).因此,leaf if if为NULL,并且if-dependent不执行,因此5不被删除.我在哪里弄错了这个推理?如何在这里进行卷绕和退绕?任何帮助都很感激:-)
mar*_*ark 12
在那一点看起来像这样:
void destroy_tree(struct node *leaf_5)
{
if( leaf_5 != 0 ) // it's not
{
destroy_tree(leaf_5->left); // it's NULL so the call does nothing
destroy_tree(leaf_5->right); // it's NULL so the call does nothing
free( leaf_5 ); // free here
}
}
Run Code Online (Sandbox Code Playgroud)
没有必要返回...步骤的"历史"在调用堆栈上,在这一点看起来像这样:
destroy_tree(leaf_10)
destroy_tree(leaf_10->left, which is leaf_6)
destroy_tree(leaf_6->left, which is leaf_5)
Run Code Online (Sandbox Code Playgroud)
所以在leaf_5消失之后,它会回到堆栈中并且destroy_tree(leaf_6->right, which is leaf_8)......等等......