构造和使用二叉树后,将二叉树的释放,需要将存储二叉树节点的内存空间释放掉,最后将二叉树置NULL。
根据前面一篇文章中二叉树的遍历可以得到启示,遍历是将节点数据元素找出来,同样利用便利的思想,也可以将节点指向的内存空间释放掉。这里需要注意的问题时,释放的先后问题,根节点必须在左子树和右子树的后面释放,因此,利用后续遍历的方法可以释放掉二叉树中多有节点的存储空间。
如下代码:
1 /释放二叉树的内存空间,将二叉树置空 2 void BTreeSetNull(BTree *tree) 3 { 4 if(tree==NULL) 5 { 6 return; 7 } 8 BTreeSetNull(tree->left); 9 BTreeSetNull(tree->right); 10 free(tree); 11 }
为了验证方法的正确性,利用内存泄漏检测工具valgrind进行检查
$ valgrind --tool=memcheck --leak-check=full ./tree
结果如下所示:
==2957== Memcheck, a memory error detector
==2957== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==2957== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==2957== Command: ./tree
==2957==
Create binary tree:
1
2
3
0
0
4
0
0
6
7
0
0
0
Pre order:
1 2 3 4 6 7
Mid order:
3 2 4 1 7 6
Post order:
3 4 2 7 6 1
==2957==
==2957== HEAP SUMMARY:
==2957== in use at exit: 0 bytes in 0 blocks
==2957== total heap usage: 6 allocs, 6 frees, 72 bytes allocated
==2957==
==2957== All heap blocks were freed -- no leaks are possible
==2957==
==2957== For counts of detected and suppressed errors, rerun with: -v
==2957== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 6)
从上面的结果可以看到,程序中不存在内存泄漏的问题,申请的6个堆空间全部释放(因为游6个节点所以申请了6个堆空间)。