用C语言创建一个字符型二叉树,计算二叉树叶子节点数和总节点数,实现先序遍历,中序遍历,后序遍历,以及层次遍历,计算二叉树的高度和宽度
时间: 2023-06-10 17:09:00 浏览: 96
好的,下面是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node* left;
struct node* right;
} Node;
// 创建二叉树
Node* createTree() {
char ch;
Node* root = NULL;
scanf("%c", &ch);
if (ch == '#') {
root = NULL;
} else {
root = (Node*)malloc(sizeof(Node));
if (root == NULL) {
printf("内存分配失败!\n");
exit(1);
}
root->data = ch;
root->left = createTree();
root->right = createTree();
}
return root;
}
// 计算二叉树叶子节点数和总节点数
void countNodes(Node* root, int* count, int* leafCount) {
if (root != NULL) {
(*count)++;
if (root->left == NULL && root->right == NULL) {
(*leafCount)++;
}
countNodes(root->left, count, leafCount);
countNodes(root->right, count, leafCount);
}
}
// 先序遍历二叉树
void preOrder(Node* root) {
if (root != NULL) {
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
// 中序遍历二叉树
void inOrder(Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
}
// 后序遍历二叉树
void postOrder(Node* root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
}
// 层次遍历二叉树
void levelOrder(Node* root) {
Node* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
Node* node = queue[front++];
printf("%c ", node->data);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
// 计算二叉树的高度
int height(Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
// 计算二叉树的宽度
int width(Node* root) {
if (root == NULL) {
return 0;
}
Node* queue[1000];
int front = 0, rear = 0, maxWidth = 0;
queue[rear++] = root;
while (front < rear) {
int count = rear - front;
if (count > maxWidth) {
maxWidth = count;
}
while (count-- > 0) {
Node* node = queue[front++];
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
return maxWidth;
}
int main() {
printf("请输入二叉树,使用'#'表示空节点:\n");
Node* root = createTree();
int count = 0, leafCount = 0;
countNodes(root, &count, &leafCount);
printf("二叉树总节点数:%d,叶子节点数:%d\n", count, leafCount);
printf("先序遍历结果:");
preOrder(root);
printf("\n");
printf("中序遍历结果:");
inOrder(root);
printf("\n");
printf("后序遍历结果:");
postOrder(root);
printf("\n");
printf("层次遍历结果:");
levelOrder(root);
printf("\n");
printf("二叉树的高度:%d\n", height(root));
printf("二叉树的宽度:%d\n", width(root));
return 0;
}
```
其中,输入二叉树的方式为从标准输入中读取字符,使用 # 表示空节点。在计算节点数和叶子节点数时,使用了指针传参的方式。在计算二叉树高度和宽度时,使用了队列来实现层次遍历。
阅读全文