diff --git a/codes/c/chapter_tree/binary_tree_bfs.c b/codes/c/chapter_tree/binary_tree_bfs.c index 8e770b491..e21d6d23a 100644 --- a/codes/c/chapter_tree/binary_tree_bfs.c +++ b/codes/c/chapter_tree/binary_tree_bfs.c @@ -15,7 +15,7 @@ int *levelOrder(TreeNode *root, int *size) { TreeNode **queue; /* 辅助队列 */ - queue = (TreeNode **)malloc(sizeof(TreeNode) * MAX_NODE_SIZE); + queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_NODE_SIZE); // 队列指针 front = 0, rear = 0; // 加入根节点 @@ -42,6 +42,9 @@ int *levelOrder(TreeNode *root, int *size) { // 更新数组长度的值 *size = index; arr = realloc(arr, sizeof(int) * (*size)); + + // 释放辅助数组空间 + free(queue); return arr; } @@ -61,5 +64,8 @@ int main() { printf("层序遍历的节点打印序列 = "); printArray(arr, size); + // 释放内存 + freeMemoryTree(root); + free(arr); return 0; } diff --git a/codes/c/utils/tree_node.h b/codes/c/utils/tree_node.h index 37816d3e4..7a1c8e4c3 100644 --- a/codes/c/utils/tree_node.h +++ b/codes/c/utils/tree_node.h @@ -49,7 +49,7 @@ TreeNode *arrToTree(const int *arr, size_t size) { /* 根节点 */ root = newTreeNode(arr[0]); /* 辅助队列 */ - queue = (TreeNode **)malloc(sizeof(TreeNode) * MAX_NODE_SIZE); + queue = (TreeNode **)malloc(sizeof(TreeNode *) * MAX_NODE_SIZE); // 队列指针 front = 0, rear = 0; // 将根节点放入队尾 @@ -75,6 +75,8 @@ TreeNode *arrToTree(const int *arr, size_t size) { } } } + // 释放辅助队列空间 + free(queue); return root; }