Skip to content

Commit

Permalink
Fix the problem in binary_tree_bfs.c and the problem that the memory…
Browse files Browse the repository at this point in the history
… is not released. (krahets#487)

* fix(codes/cpp): Memory leak fix: the space was not freed when pop removed the element.

* fix(codes/cpp): Fix access error when printArray(arr, 0)

* Update PrintUtil.hpp

* fix(codes/c): Fix some errors of cmake build

* feat(codes/c): Add hashing_search.c

* styles(codes/c): Modify function description

* styles(codes/c): Modify binary_search.c code style

* fix(codes/c): Fix the problem in binary_tree_bfs.c and the problem that the memory is not released.

---------

Co-authored-by: Yudong Jin <[email protected]>
  • Loading branch information
Gonglja and krahets authored May 8, 2023
1 parent a6c5f10 commit 53ca214
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
8 changes: 7 additions & 1 deletion codes/c/chapter_tree/binary_tree_bfs.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
// 加入根节点
Expand All @@ -42,6 +42,9 @@ int *levelOrder(TreeNode *root, int *size) {
// 更新数组长度的值
*size = index;
arr = realloc(arr, sizeof(int) * (*size));

// 释放辅助数组空间
free(queue);
return arr;
}

Expand All @@ -61,5 +64,8 @@ int main() {
printf("层序遍历的节点打印序列 = ");
printArray(arr, size);

// 释放内存
freeMemoryTree(root);
free(arr);
return 0;
}
4 changes: 3 additions & 1 deletion codes/c/utils/tree_node.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
// 将根节点放入队尾
Expand All @@ -75,6 +75,8 @@ TreeNode *arrToTree(const int *arr, size_t size) {
}
}
}
// 释放辅助队列空间
free(queue);
return root;
}

Expand Down

0 comments on commit 53ca214

Please sign in to comment.