c语言给二叉树的根节点,返回节点值的层序遍历
时间: 2024-01-05 11:47:59 浏览: 82
可以使用队列实现层序遍历。具体过程如下:
1. 将根节点入队列。
2. 当队列非空时,依次出队列队首元素。
3. 将出队元素的值存储到结果数组中。
4. 将出队元素的左右子节点入队列(如果存在)。
5. 重复步骤2-4,直到队列为空。
以下是C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Queue {
TreeNode *data[MAXSIZE];
int front, rear;
} Queue;
void initQueue(Queue *q);
int isEmpty(Queue *q);
int isFull(Queue *q);
void enQueue(Queue *q, TreeNode *node);
TreeNode *deQueue(Queue *q);
void levelOrder(TreeNode *root, int *result, int *returnSize);
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isEmpty(Queue *q) {
return q->front == q->rear;
}
int isFull(Queue *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
void enQueue(Queue *q, TreeNode *node) {
if (isFull(q)) {
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAXSIZE;
}
TreeNode *deQueue(Queue *q) {
if (isEmpty(q)) {
return NULL;
}
TreeNode *node = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return node;
}
void levelOrder(TreeNode *root, int *result, int *returnSize) {
if (root == NULL) {
return;
}
Queue q;
initQueue(&q);
enQueue(&q, root);
while (!isEmpty(&q)) {
TreeNode *node = deQueue(&q);
result[(*returnSize)++] = node->val;
if (node->left != NULL) {
enQueue(&q, node->left);
}
if (node->right != NULL) {
enQueue(&q, node->right);
}
}
}
int main() {
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = NULL;
root->left->right = NULL;
root->right->left = (TreeNode *) malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right->left = NULL;
root->right->right->right = NULL;
int result[MAXSIZE], returnSize = 0;
levelOrder(root, result, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
```
阅读全文