recursive delete on a binary tree

后端 未结 2 1651
夕颜
夕颜 2021-01-05 07:59

I am trying to understand how the recursive method of deletion of a binary search tree works. The code that I came across in many places looks as follows:

vo         


        
2条回答
  •  清歌不尽
    2021-01-05 08:32

    It looks like this at that point:

    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
      }
    }
    

    Nothing is required to return... the "history" of the steps is on the call stack, which looks something like this at that point:

    destroy_tree(leaf_10)
      destroy_tree(leaf_10->left, which is leaf_6)
        destroy_tree(leaf_6->left, which is leaf_5)
    

    So after leaf_5 is gone, it goes back up the stack and does destroy_tree(leaf_6->right, which is leaf_8)... etc...

提交回复
热议问题