mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
feat(tree): add C codes
This commit is contained in:
66
codes/c/chapter_tree/binary_tree_bfs.c
Normal file
66
codes/c/chapter_tree/binary_tree_bfs.c
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: binary_tree_bfs.c
|
||||
* Created Time: 2023-01-11
|
||||
* Author: Reanon (793584285@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.h"
|
||||
|
||||
/* 层序遍历 */
|
||||
int *levelOrder(TreeNode *root, int *size) {
|
||||
/* 辅助队列 */
|
||||
int front, rear;
|
||||
int index, *arr;
|
||||
TreeNode *node;
|
||||
TreeNode **queue;
|
||||
|
||||
/* 辅助队列 */
|
||||
queue = (TreeNode **) malloc(sizeof(TreeNode) * MAX_NODE_SIZE);
|
||||
// 队列指针
|
||||
front = 0, rear = 0;
|
||||
// 加入根结点
|
||||
queue[rear++] = root;
|
||||
// 初始化一个列表,用于保存遍历序列
|
||||
/* 辅助数组 */
|
||||
arr = (int *) malloc(sizeof(int) * MAX_NODE_SIZE);
|
||||
// 数组指针
|
||||
index = 0;
|
||||
while (front < rear) {
|
||||
// 队列出队
|
||||
node = queue[front++];
|
||||
// 保存结点
|
||||
arr[index++] = node->val;
|
||||
if (node->left != NULL) {
|
||||
// 左子结点入队
|
||||
queue[rear++] = node->left;
|
||||
}
|
||||
if (node->right != NULL) {
|
||||
// 右子结点入队
|
||||
queue[rear++] = node->right;
|
||||
}
|
||||
}
|
||||
// 更新数组长度的值
|
||||
*size = index;
|
||||
arr = realloc(arr, sizeof(int) * (*size));
|
||||
return arr;
|
||||
}
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
int nums[] = {1, 2, 3, NIL, 5, 6, NIL};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
TreeNode *root = ArrayToTree(nums, size);
|
||||
printf("初始化二叉树\n");
|
||||
PrintTree(root);
|
||||
|
||||
/* 层序遍历 */
|
||||
// 需要传入数组的长度
|
||||
int *arr = levelOrder(root, &size);
|
||||
printf("层序遍历的结点打印序列 = ");
|
||||
PrintArray(arr, size);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user