以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数,c语言解答
时间: 2023-06-16 10:03:18 浏览: 122
下面是用C语言实现层次遍历二叉树并统计度为1的节点个数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点结构体
typedef struct TreeNode{
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode *data[100];
int front;
int rear;
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 入队
void enQueue(Queue *queue, TreeNode *node) {
queue->data[queue->rear++] = node;
}
// 出队
TreeNode* deQueue(Queue *queue) {
return queue->data[queue->front++];
}
// 判断队列是否为空
int isQueueEmpty(Queue *queue) {
return queue->front == queue->rear;
}
// 层次遍历二叉树并统计度为1的节点个数
int levelOrderTraversal(TreeNode *root) {
if (root == NULL) {
return 0;
}
Queue *queue = (Queue*)malloc(sizeof(Queue));
initQueue(queue);
enQueue(queue, root);
int count = 0;
while (!isQueueEmpty(queue)) {
TreeNode *node = deQueue(queue);
if (node->left != NULL && node->right == NULL) {
count++;
}
if (node->left == NULL && node->right != NULL) {
count++;
}
if (node->left != NULL) {
enQueue(queue, node->left);
}
if (node->right != NULL) {
enQueue(queue, node->right);
}
}
return count;
}
int main() {
// 构造二叉树
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = 1;
TreeNode *node1 = (TreeNode*)malloc(sizeof(TreeNode));
node1->data = 2;
TreeNode *node2 = (TreeNode*)malloc(sizeof(TreeNode));
node2->data = 3;
TreeNode *node3 = (TreeNode*)malloc(sizeof(TreeNode));
node3->data = 4;
TreeNode *node4 = (TreeNode*)malloc(sizeof(TreeNode));
node4->data = 5;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = NULL;
node2->left = NULL;
node2->right = node4;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
// 层次遍历并统计度为1的节点个数
int count = levelOrderTraversal(root);
printf("度为1的节点个数为:%d\n", count);
return 0;
}
```
上述代码中,我们使用队列来实现二叉树的层次遍历,然后判断每个节点的左右子树是否为空,从而统计度为1的节点个数。
阅读全文