删除一颗二叉树

To delete a tree we must traverse all the nodes of the tree and delete them one by one. So which traversal we should use – Inorder or Preorder or Postorder.Answer is simple – Postorder, because before deleting the parent node we should delete its children nodes first。

/*
  This function is same as deleteTree() in the previous program
 */
void _deleteTree(struct node* node)
{
    if (node == NULL) return;
 
    /* first delete both subtrees */
    _deleteTree(node->left);
    _deleteTree(node->right);
 
    /* then delete the node */
    printf("\n Deleting node: %d", node->data);
    free(node);
}
 
/* Deletes a tree and sets the root as NULL */
void deleteTree(struct node** node_ref)
{
  _deleteTree(*node_ref);
  *node_ref = NULL;
}
    原文作者:lintong
    原文地址: https://www.jianshu.com/p/013652a19d4f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞