C语言层次遍历创建二叉树
时间: 2023-11-11 11:06:41 浏览: 101
C语言层次遍历二叉树
语言中,层次遍历创建二叉树的过程可以通过队列来实现。具体步骤如下:
1. 定义二叉树结构体和队列结构体,以及相应的入队和出队操作函数。
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct QueueNode {
TreeNode *node;
struct QueueNode *next;
} QueueNode;
typedef struct Queue {
QueueNode *front;
QueueNode *rear;
} Queue;
void enqueue(Queue *q, TreeNode *node) {
QueueNode *newNode = (QueueNode*)malloc(sizeof(QueueNode));
newNode->node = node;
newNode->next = NULL;
if (q->rear) {
q->rear->next = newNode;
} else {
q->front = newNode;
}
q->rear = newNode;
}
TreeNode* dequeue(Queue *q) {
if (!q->front) {
return NULL;
}
TreeNode *node = q->front->node;
QueueNode *temp = q->front;
q->front = q->front->next;
if (!q->front) {
q->rear = NULL;
}
free(temp);
return node;
}
```
2. 定义层次遍历创建二叉树的函数,函数参数为一个整型数组和数组长度,返回值为二叉树的根节点。
```c
TreeNode* createTree(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 q = {NULL, NULL};
enqueue(&q, root);
int i = 1;
while (i < numsSize) {
TreeNode *parent = dequeue(&q);
if (i < numsSize) {
TreeNode *left = (TreeNode*)malloc(sizeof(TreeNode));
left->val = nums[i++];
left->left = NULL;
left->right = NULL;
parent->left = left;
enqueue(&q, left);
}
if (i < numsSize) {
TreeNode *right = (TreeNode*)malloc(sizeof(TreeNode));
right->val = nums[i++];
right->left = NULL;
right->right = NULL;
parent->right = right;
enqueue(&q, right);
}
}
return root;
}
```
3. 调用层次遍历创建二叉树的函数,传入一个整型数组和数组长度,即可得到创建好的二叉树的根节点。
```c
int nums[] = {1, 2, 3, 4, 5, 6, 7};
int numsSize = sizeof(nums) / sizeof(int);
TreeNode *root = createTree(nums, numsSize);
```
阅读全文