销毁一颗二叉树【数据结构】

销毁一颗二叉树
销毁树与遍历操作类似,即遍历一个节点释放

   如果采用先序遍历或者中序遍历,销毁根节点后就找不到左右孩子
在销毁的时候需要保存左右孩子的地址。

因此采用后序遍历销毁一颗二叉树,按照左孩子,右孩子,根节点的顺序销毁,
注意:根节点将根节点指向空,防止成为野指针。

340 void DestroyNode(TreeNode* node)
341 {
342     free(node);
343     return ;
344 }
345 
346 void TreeDestroy(TreeNode** root)
347 {
348     if(root==NULL)
349     {
350         //非法
351         return ;
352     }
353     if(*root==NULL)
354     {
355         //空树
356         return ;
357     }
358     TreeDestroy(&((*root)->lchild));
359     TreeDestroy(&((*root)->rchild));
360     DestroyNode(*root);
361     *root=NULL;
362     return ;
363 }  

猜你喜欢

转载自blog.csdn.net/yu876876/article/details/80952165
今日推荐