给我二叉树层次遍历的c++代码
时间: 2023-12-28 07:06:11 浏览: 76
当然,下面是二叉树层次遍历的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
//树节点的结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
//队列节点的结构体
struct QueueNode {
struct TreeNode *data;
struct QueueNode *next;
};
//队列的结构体
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;
};
//初始化队列
void initQueue(struct Queue *q) {
q->front = NULL;
q->rear = NULL;
}
//入队操作
void enQueue(struct Queue *q, struct TreeNode *data) {
struct QueueNode *node = (struct QueueNode*)malloc(sizeof(struct QueueNode));
node->data = data;
node->next = NULL;
if(q->rear == NULL) {
q->front = node;
q->rear = node;
} else {
q->rear->next = node;
q->rear = node;
}
}
//出队操作
struct TreeNode* deQueue(struct Queue *q) {
if(q->front == NULL) {
return NULL;
}
struct QueueNode *node = q->front;
if(q->front == q->rear) {
q->front = NULL;
q->rear = NULL;
} else {
q->front = q->front->next;
}
struct TreeNode *data = node->data;
free(node);
return data;
}
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
//定义一个二维数组来保存遍历结果
int **result = (int**)malloc(sizeof(int*) * 1000);
*returnColumnSizes = (int*)malloc(sizeof(int) * 1000);
struct Queue q;
*returnSize = 0;
if(root == NULL) {
return result;
}
initQueue(&q);
enQueue(&q, root);
while(q.front != NULL) {
int size = q.rear - q.front + 1;
int *temp = (int*)malloc(sizeof(int) * size);
for(int i = 0; i < size; i++) {
struct TreeNode *node = deQueue(&q);
temp[i] = node->val;
if(node->left != NULL) {
enQueue(&q, node->left);
}
if(node->right != NULL) {
enQueue(&q, node->right);
}
}
(*returnColumnSizes)[*returnSize] = size;
result[*returnSize] = temp;
(*returnSize)++;
}
return result;
}
```
希望能够帮到您!
阅读全文