c语言使用队列按层次遍历建立二叉树
时间: 2024-02-21 18:33:10 浏览: 88
借助队列实现二叉树的层次遍历 (C语言)
5星 · 资源好评率100%
在C语言中,我们可以使用队列按层次遍历建立二叉树。
具体实现步骤如下:
1. 定义二叉树节点结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
2. 定义队列结构体:
```c
typedef struct QueueNode {
TreeNode *treenode;
struct QueueNode *next;
} QueueNode;
typedef struct Queue {
QueueNode *front;
QueueNode *rear;
} Queue;
```
3. 实现队列的入队、出队、判空操作:
```c
void enqueue(Queue *q, TreeNode *treenode) {
QueueNode *node = (QueueNode *)malloc(sizeof(QueueNode));
node->treenode = treenode;
node->next = NULL;
if (q->front == NULL) {
q->front = node;
} else {
q->rear->next = node;
}
q->rear = node;
}
TreeNode *dequeue(Queue *q) {
if (q->front == NULL) {
return NULL;
}
TreeNode *treenode = q->front->treenode;
QueueNode *temp = q->front;
q->front = q->front->next;
free(temp);
return treenode;
}
bool isEmpty(Queue *q) {
return q->front == NULL;
}
```
4. 实现按层次遍历建立二叉树的函数:
```c
TreeNode *createBinaryTreeByLevelOrder(void) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->front = q->rear = NULL;
TreeNode *root = NULL;
int val;
printf("请输入根节点的值:");
scanf("%d", &val);
if (val == -1) {
return NULL;
}
root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = val;
root->left = root->right = NULL;
enqueue(q, root);
while (!isEmpty(q)) {
TreeNode *parent = dequeue(q);
printf("请输入%d节点的左子节点的值:", parent->val);
scanf("%d", &val);
if (val != -1) {
TreeNode *left = (TreeNode *)malloc(sizeof(TreeNode));
left->val = val;
left->left = left->right = NULL;
parent->left = left;
enqueue(q, left);
}
printf("请输入%d节点的右子节点的值:", parent->val);
scanf("%d", &val);
if (val != -1) {
TreeNode *right = (TreeNode *)malloc(sizeof(TreeNode));
right->val = val;
right->left = right->right = NULL;
parent->right = right;
enqueue(q, right);
}
}
return root;
}
```
完整代码如下:
阅读全文