简体   繁体   中英

BST pre-order deletion

I would like to know if it is possible to free an entire binary search tree in preorder mode. I've got this function:

void preorder_del(struct s_nodo ** tree)
{
     if (*tree != NULL)
        {
          free(*tree);
          preorder_del(&(*tree)->left);
          preorder_del(&(*tree)->right);
        }
}

I don't think this works, freeing the first leaf of the tree wont let me recall preorder, right?

You should record left and right locally to avoid accessing freed pointer after free(*tree) .

 if (*tree != NULL)
 {
      struct s_nodo *l = (*tree)->left;
      struct s_nodo *r = (*tree)->right;
      free(*tree);
      preorder_del(&l);
      preorder_del(&r);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM