c语言实现,以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数。
时间: 2023-06-14 10:06:24 浏览: 120
实现思路:
1. 定义二叉树的结构体,包括数据域和左右孩子指针;
2. 定义一个队列,用于存储待遍历的结点;
3. 将根结点入队,然后开始遍历队列,每次取出队首结点,将其左右孩子结点入队;
4. 遍历过程中,统计度为1的结点个数。
代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct QueueNode {
TreeNode *data;
struct QueueNode *next;
} QueueNode;
typedef struct Queue {
QueueNode *front;
QueueNode *rear;
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = NULL;
queue->rear = NULL;
}
// 入队
void enqueue(Queue *queue, TreeNode *node) {
QueueNode *newNode = (QueueNode *)malloc(sizeof(QueueNode));
newNode->data = node;
newNode->next = NULL;
if (queue->rear == NULL) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
// 出队
TreeNode *dequeue(Queue *queue) {
if (queue->front == NULL) {
return NULL;
} else {
TreeNode *data = queue->front->data;
QueueNode *temp = queue->front;
queue->front = temp->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
return data;
}
}
// 层次遍历
void levelOrderTraversal(TreeNode *root, int *count) {
if (root == NULL) {
return;
}
Queue queue;
initQueue(&queue);
enqueue(&queue, root);
while (queue.front != NULL) {
TreeNode *node = dequeue(&queue);
if (node->left != NULL) {
enqueue(&queue, node->left);
}
if (node->right != NULL) {
enqueue(&queue, node->right);
}
if ((node->left == NULL && node->right != NULL) || (node->left != NULL && node->right == NULL)) {
(*count)++;
}
}
}
int main() {
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = 1;
TreeNode *node2 = (TreeNode *)malloc(sizeof(TreeNode));
node2->data = 2;
TreeNode *node3 = (TreeNode *)malloc(sizeof(TreeNode));
node3->data = 3;
TreeNode *node4 = (TreeNode *)malloc(sizeof(TreeNode));
node4->data = 4;
TreeNode *node5 = (TreeNode *)malloc(sizeof(TreeNode));
node5->data = 5;
root->left = node2;
root->right = node3;
node2->left = node4;
node2->right = NULL;
node3->left = NULL;
node3->right = node5;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
int count = 0;
levelOrderTraversal(root, &count);
printf("度为1的结点个数为:%d\n", count);
return 0;
}
```
运行结果:
```
度为1的结点个数为:2
```
阅读全文