C语言求取二叉树每层结点的个数
时间: 2023-05-26 13:04:15 浏览: 123
下面是C语言实现二叉树每层结点个数的代码:
```
#include <stdio.h>
#include <stdlib.h>
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;
// 创建二叉树节点
TreeNode* createNode(int val) {
TreeNode *node = (TreeNode*) malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 向队列中添加元素
void enqueue(Queue *q, TreeNode *node) {
QueueNode *qNode = (QueueNode*) malloc(sizeof(QueueNode));
qNode->node = node;
qNode->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = qNode;
} else {
q->rear->next = qNode;
q->rear = qNode;
}
}
// 从队列中删除元素
TreeNode* dequeue(Queue *q) {
if (q->front == NULL) {
return NULL;
} else {
QueueNode *node = q->front;
TreeNode *tnode = node->node;
q->front = q->front->next;
free(node);
if (q->front == NULL) {
q->rear = NULL;
}
return tnode;
}
}
// 获取二叉树每层节点数量
int* levelOrder(TreeNode *root, int *returnSize) {
int *res = (int*) malloc(sizeof(int) * 1000);
int level = 0, count = 0;
Queue *queue = (Queue*) malloc(sizeof(Queue));
queue->front = queue->rear = NULL;
enqueue(queue, root);
while (queue->front != NULL) {
level++;
count = 0;
int n = queue->rear - queue->front + 1;
for (int i = 0; i < n; i++) {
TreeNode *node = dequeue(queue);
if (node != NULL) {
count++;
if (node->left != NULL) {
enqueue(queue, node->left);
}
if (node->right != NULL) {
enqueue(queue, node->right);
}
}
}
res[level - 1] = count;
}
*returnSize = level;
return res;
}
int main() {
TreeNode *node1 = createNode(3);
TreeNode *node2 = createNode(9);
TreeNode *node3 = createNode(20);
TreeNode *node4 = createNode(15);
TreeNode *node5 = createNode(7);
TreeNode *node6 = createNode(8);
TreeNode *node7 = createNode(10);
node1->left = node2;
node1->right = node3;
node3->left = node4;
node3->right = node5;
node4->left = node6;
node5->right = node7;
int size = 0;
int *res = levelOrder(node1, &size);
for (int i = 0; i < size; i++) {
printf("%d ", res[i]);
}
free(res);
return 0;
}
```
该代码实现了二叉树的遍历,使用队列将每个结点加入队列,并在出队的过程中统计每层的结点数量,最终得到每层的结点数量并返回。
阅读全文