以二叉链表作为二叉树的存储结构,用c语言编写以下算法并在main函数中使用: (1)统计二叉树的叶结点个数 (2)判断两棵二叉树是否相等 (3)交换二叉树每个结点的左孩子和右孩子 (4)按照层序遍历二叉树,统计树中度为1的结点个数
时间: 2023-10-18 12:07:53 浏览: 95
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点结构体
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树结点
TreeNode *create_node(int data) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 统计二叉树的叶子节点个数
int count_leaf_nodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return count_leaf_nodes(root->left) + count_leaf_nodes(root->right);
}
// 判断两棵二叉树是否相等
int is_same_tree(TreeNode *p, TreeNode *q) {
if (p == NULL && q == NULL) {
return 1;
}
if (p == NULL || q == NULL) {
return 0;
}
if (p->data != q->data) {
return 0;
}
return is_same_tree(p->left, q->left) && is_same_tree(p->right, q->right);
}
// 交换二叉树每个结点的左孩子和右孩子
void swap_left_right(TreeNode *root) {
if (root == NULL) {
return;
}
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
swap_left_right(root->left);
swap_left_right(root->right);
}
// 按照层序遍历二叉树,统计树中度为1的结点个数
int count_degree_one_nodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
int count = 0;
TreeNode *queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode *node = queue[front++];
if ((node->left == NULL && node->right != NULL) || (node->left != NULL && node->right == NULL)) {
count++;
}
if (node->left) {
queue[rear++] = node->left;
}
if (node->right) {
queue[rear++] = node->right;
}
}
return count;
}
int main() {
// 创建一棵二叉树
TreeNode *root = create_node(1);
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->left->right = create_node(5);
root->right->left = create_node(6);
root->right->right = create_node(7);
// 统计二叉树的叶子节点个数
int leaf_count = count_leaf_nodes(root);
printf("叶子节点个数: %d\n", leaf_count);
// 判断两棵二叉树是否相等
TreeNode *root2 = create_node(1);
root2->left = create_node(2);
root2->right = create_node(3);
root2->left->left = create_node(4);
root2->left->right = create_node(5);
root2->right->left = create_node(6);
root2->right->right = create_node(7);
int same = is_same_tree(root, root2);
printf("两棵二叉树是否相等: %d\n", same);
// 交换二叉树每个结点的左右孩子
swap_left_right(root);
printf("交换左右孩子后的二叉树:\n");
printf(" %d\n", root->data);
printf(" %d %d\n", root->left->data, root->right->data);
printf(" %d %d %d %d\n", root->left->left->data, root->left->right->data, root->right->left->data, root->right->right->data);
// 按照层序遍历二叉树,统计树中度为1的结点个数
int degree_one_count = count_degree_one_nodes(root);
printf("度为1的结点个数: %d\n", degree_one_count);
return 0;
}
```
阅读全文