以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数。(c语言实现)
时间: 2024-05-13 07:16:25 浏览: 113
以下是使用二叉链表存储二叉树,并用队列实现层次遍历的代码,同时统计度为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;
// 创建二叉树结点
TreeNode* createTreeNode(int data) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 将二叉树以层次顺序遍历的方式存储到二叉链表中
void createBinaryTree(TreeNode** root, int data[], int n) {
if (n <= 0) {
*root = NULL;
return;
}
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = NULL;
queue->rear = NULL;
*root = createTreeNode(data[0]);
QueueNode* queueNode = (QueueNode*)malloc(sizeof(QueueNode));
queueNode->data = *root;
queueNode->next = NULL;
queue->front = queueNode;
queue->rear = queueNode;
int i;
for (i = 1; i < n; i += 2) {
TreeNode* parent = queue->front->data;
if (data[i] != -1) {
parent->left = createTreeNode(data[i]);
queueNode = (QueueNode*)malloc(sizeof(QueueNode));
queueNode->data = parent->left;
queueNode->next = NULL;
queue->rear->next = queueNode;
queue->rear = queueNode;
}
if (i + 1 < n && data[i + 1] != -1) {
parent->right = createTreeNode(data[i + 1]);
queueNode = (QueueNode*)malloc(sizeof(QueueNode));
queueNode->data = parent->right;
queueNode->next = NULL;
queue->rear->next = queueNode;
queue->rear = queueNode;
}
queueNode = queue->front;
queue->front = queue->front->next;
free(queueNode);
}
}
// 统计树中度为1的结点个数
int countDegree1Nodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right != NULL) {
return 1 + countDegree1Nodes(root->right);
}
if (root->left != NULL && root->right == NULL) {
return 1 + countDegree1Nodes(root->left);
}
return countDegree1Nodes(root->left) + countDegree1Nodes(root->right);
}
int main() {
int data[] = {1, 2, 3, -1, -1, 4, -1, -1, 5, 6, -1, -1, 7, -1, -1};
TreeNode* root;
createBinaryTree(&root, data, sizeof(data) / sizeof(data[0]));
printf("The number of degree 1 nodes is %d.\n", countDegree1Nodes(root));
return 0;
}
```
在这个例子中,我们创建了一棵二叉树,它的层次遍历顺序为1 2 3 -1 -1 4 -1 -1 5 6 -1 -1 7 -1 -1。其中,-1表示空节点。这棵树的形状如下:
```
1
/ \
2 3
/
4
\
5
/ \
6 7
```
这棵树中,度为1的节点有4个,分别是2、4、5和7。因此,程序输出的结果为"The number of degree 1 nodes is 4."。
阅读全文