c语言编写代码 实验要求 二叉树可以任意输入建立并显示二叉树;能友好的显示各种结果; 对于二叉树的输入,空用“^”表示。 首先输入一个二叉树。然后输出: 先序遍历结果“=:先序遍历结果回车”; 中序遍历结果“=:中序遍历结果回车”; 后序遍历结果“=:后序遍历结果回车”; 层序遍历结果“=:层序遍历结果回车”; 叶子数“=:叶子数” 树的深度“=:树的深度回车”。
时间: 2023-08-14 14:06:03 浏览: 79
以下是用C语言编写的二叉树代码,可以任意输入建立并显示二叉树;能友好的显示各种结果;对于二叉树的输入,空用“^”表示:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
void createTree(TreeNode** root) {
char ch;
scanf("%c", &ch);
if (ch == '^') {
*root = NULL;
} else {
*root = (TreeNode*)malloc(sizeof(TreeNode));
(*root)->data = ch;
createTree(&((*root)->left));
createTree(&((*root)->right));
}
}
void preOrder(TreeNode* root) {
if (root != NULL) {
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode* root) {
if (root != NULL) {
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
}
void postOrder(TreeNode* root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
}
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode* node = queue[front++];
printf("%c ", node->data);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
int countLeaves(TreeNode* root) {
if (root == NULL) {
return 0;
} else if (root->left == NULL && root->right == NULL) {
return 1;
} else {
return countLeaves(root->left) + countLeaves(root->right);
}
}
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return (leftDepth > rightDepth) ? leftDepth + 1 : rightDepth + 1;
}
}
int main() {
TreeNode* root;
createTree(&root);
printf("先序遍历结果=");
preOrder(root);
printf("\n");
printf("中序遍历结果=");
inOrder(root);
printf("\n");
printf("后序遍历结果=");
postOrder(root);
printf("\n");
printf("层序遍历结果=");
levelOrder(root);
printf("\n");
printf("叶子数=%d\n", countLeaves(root));
printf("树的深度=%d\n", maxDepth(root));
return 0;
}
```
其中,createTree函数用于输入建立二叉树;preOrder、inOrder、postOrder、levelOrder分别为先序遍历、中序遍历、后序遍历、层序遍历的函数;countLeaves函数用于计算叶子数;maxDepth函数用于计算二叉树的深度。最后在main函数中调用这些函数输出结果。
阅读全文