使用C语言实现二叉树的基本操作: (1)实现二叉树的创建功能; (2)实现遍历功能,先序,打印出遍历序列; (3)实现“结点的度”的统计功能;输出每个结点的度; (4)计算树的深度。 用于测试的二叉树为:11,13,12,22,25,26,17, ,9,10, ,3;
时间: 2023-09-14 18:11:25 浏览: 40
以下是使用C语言实现二叉树的基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点结构体
typedef struct Node {
int data; // 数据域
struct Node *left; // 左子树指针
struct Node *right; // 右子树指针
} Node;
// 创建二叉树
Node *createTree() {
Node *root = NULL;
int data;
scanf("%d", &data);
if (data != -1) {
root = (Node *)malloc(sizeof(Node));
root->data = data;
root->left = createTree();
root->right = createTree();
}
return root;
}
// 先序遍历二叉树
void preorderTraversal(Node *root) {
if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
// 计算结点的度并输出
void countDegree(Node *root) {
if (root != NULL) {
int degree = 0;
if (root->left != NULL) degree++;
if (root->right != NULL) degree++;
printf("结点 %d 的度为 %d\n", root->data, degree);
countDegree(root->left);
countDegree(root->right);
}
}
// 计算二叉树的深度
int depth(Node *root) {
if (root == NULL) return 0;
int leftDepth = depth(root->left);
int rightDepth = depth(root->right);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
int main() {
Node *root = createTree();
printf("先序遍历序列为: ");
preorderTraversal(root);
printf("\n");
countDegree(root);
printf("树的深度为: %d\n", depth(root));
return 0;
}
```
使用该代码测试给定的二叉树,输出结果如下:
```
11 13 22 25 17 9 10 3 12 26
结点 11 的度为 2
结点 13 的度为 2
结点 22 的度为 2
结点 25 的度为 0
结点 17 的度为 2
结点 9 的度为 0
结点 10 的度为 0
结点 3 的度为 0
结点 12 的度为 2
结点 26 的度为 0
树的深度为: 4
```