用C语言实现二叉树的基本操作: (1)实现二叉树的创建功能; (2)实现遍历功能,先序;打印出遍历序列; (3)实现“结点的度”的统计功能;输出每个结点的度;(4)计算树的深度。
时间: 2024-02-05 15:14:05 浏览: 12
下面是用C语言实现二叉树的基本操作的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
Node *createNode(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node *createTree() {
int data;
printf("Enter data (-1 for no node): ");
scanf("%d", &data);
if (data == -1) {
return NULL;
}
Node *root = createNode(data);
printf("Enter left child of %d:\n", data);
root->left = createTree();
printf("Enter right child of %d:\n", data);
root->right = createTree();
return root;
}
void preorder(Node *root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void countDegree(Node *root) {
if (root == NULL) {
return;
}
int degree = 0;
if (root->left != NULL) {
degree++;
}
if (root->right != NULL) {
degree++;
}
printf("Node %d has degree %d\n", root->data, degree);
countDegree(root->left);
countDegree(root->right);
}
int treeDepth(Node *root) {
if (root == NULL) {
return 0;
}
int leftDepth = treeDepth(root->left);
int rightDepth = treeDepth(root->right);
return (leftDepth > rightDepth) ? leftDepth + 1 : rightDepth + 1;
}
int main() {
Node *root = createTree();
printf("Preorder traversal: ");
preorder(root);
printf("\n");
countDegree(root);
int depth = treeDepth(root);
printf("Tree depth: %d\n", depth);
return 0;
}
```
运行示例:
```
Enter data (-1 for no node): 1
Enter left child of 1:
Enter data (-1 for no node): 2
Enter left child of 2:
Enter data (-1 for no node): -1
Enter right child of 2:
Enter data (-1 for no node): -1
Enter right child of 1:
Enter data (-1 for no node): 3
Enter left child of 3:
Enter data (-1 for no node): -1
Enter right child of 3:
Enter data (-1 for no node): -1
Preorder traversal: 1 2 3
Node 1 has degree 2
Node 2 has degree 0
Node 3 has degree 0
Tree depth: 2
```
阅读全文