構造和使用二叉樹后,將二叉樹的釋放,需要將存儲二叉樹節點的內存空間釋放掉,最后將二叉樹置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個堆空間)。
