用c语言编写代码并标出注释:通过输入一棵二叉树的层次遍历序列构造一棵二叉树
时间: 2023-05-21 08:01:20 浏览: 112
二叉树的层次遍历(c语言)
5星 · 资源好评率100%
以下是用 C 语言编写的代码,用于通过输入一棵二叉树的层次遍历序列构造一棵二叉树:
```
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode **data;
int front;
int rear;
int size;
} Queue;
// 初始化队列
Queue *initQueue(int size) {
Queue *queue = (Queue *) malloc(sizeof(Queue));
queue->data = (TreeNode **) malloc(sizeof(TreeNode *) * size);
queue->front = 0;
queue->rear = 0;
queue->size = size;
return queue;
}
// 入队
void enqueue(Queue *queue, TreeNode *node) {
if (queue->rear == queue->size) {
printf("Queue is full.\n");
return;
}
queue->data[queue->rear++] = node;
}
// 出队
TreeNode *dequeue(Queue *queue) {
if (queue->front == queue->rear) {
printf("Queue is empty.\n");
return NULL;
}
return queue->data[queue->front++];
}
// 构造二叉树
TreeNode *buildTree(int *nums, int numsSize) {
if (numsSize == 0) {
return NULL;
}
// 创建根节点
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->val = nums[0];
root->left = NULL;
root->right = NULL;
// 创建队列
Queue *queue = initQueue(numsSize);
enqueue(queue, root);
// 遍历数组
int i = 1;
while (i < numsSize) {
// 取出队首元素
TreeNode *node = dequeue(queue);
// 创建左子节点
if (i < numsSize && nums[i] != -1) {
TreeNode *left = (TreeNode *) malloc(sizeof(TreeNode));
left->val = nums[i];
left->left = NULL;
left->right = NULL;
node->left = left;
enqueue(queue, left);
}
i++;
// 创建右子节点
if (i < numsSize && nums[i] != -1) {
TreeNode *right = (TreeNode *) malloc(sizeof(TreeNode));
right->val = nums[i];
right->left = NULL;
right->right = NULL;
node->right = right;
enqueue(queue, right);
}
i++;
}
return root;
}
// 打印二叉树
void printTree(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
printTree(root->left);
printTree(root->right);
}
int main() {
int nums[] = {1, 2, 3, 4, -1, 5, 6, -1, -1, 7, -1, -1, -1, -1, -1};
int numsSize = sizeof(nums) / sizeof(int);
TreeNode *root = buildTree(nums, numsSize);
printTree(root);
return 0;
}
```
注释已经标出,代码中使用了队列来辅助构造二叉树。
阅读全文