以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数。用c语言
时间: 2023-06-13 14:09:11 浏览: 298
编写采用二叉链表形式存储的二叉树的创建、先序、中序、后序和按层遍历的算法
5星 · 资源好评率100%
二叉树的层次遍历可以使用队列实现,具体过程如下:
1. 创建一个队列,并将根节点入队;
2. 当队列不为空时,依次取出队首节点,输出其值,并将其左右子节点入队;
3. 重复步骤2,直到队列为空。
对于统计度为1的节点个数,可以在遍历过程中进行判断,如果一个节点只有左子树或右子树,则该节点的度为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* data) {
QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
node->data = data;
node->next = NULL;
if (queue->rear == NULL) {
queue->front = node;
queue->rear = node;
} else {
queue->rear->next = node;
queue->rear = node;
}
}
// 出队
TreeNode* dequeue(Queue* queue) {
if (queue->front == NULL) {
return NULL;
}
TreeNode* data = queue->front->data;
QueueNode* temp = queue->front;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
return data;
}
// 层次遍历并统计度为1的节点个数
int levelOrderTraversal(TreeNode* root) {
if (root == NULL) {
return 0;
}
Queue queue;
initQueue(&queue);
enqueue(&queue, root);
int count = 0;
while (queue.front != NULL) {
TreeNode* node = dequeue(&queue);
if (node->left != NULL && node->right != NULL) {
enqueue(&queue, node->left);
enqueue(&queue, node->right);
} else if (node->left != NULL) {
enqueue(&queue, node->left);
count++;
} else if (node->right != NULL) {
enqueue(&queue, node->right);
count++;
}
}
return count;
}
int main() {
// 构造二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->data = 2;
root->left->left = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->data = 3;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->data = 4;
root->right->left = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->data = 5;
root->right->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->left->data = 6;
root->right->right->left->left = NULL;
root->right->right->left->right = NULL;
root->right->right->right = NULL;
int count = levelOrderTraversal(root);
printf("度为1的节点个数为:%d\n", count);
return 0;
}
```
阅读全文