用c语言写一段代码完成以下要求,由客户输入二叉树的长度(序列的存储位置)、先序序列和中序序列,用层序遍历输出二叉树数据,并输出二叉树的节点个数(节点个数要计算出来)及其每个节点的子点个数
时间: 2024-03-17 09:44:17 浏览: 64
关于一个数据结构的一个i算法的描述,是二叉树的遍历问题,只有源代码,但是是可以直接运行的,是用C写的二叉树遍历问题.zip
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode, *pTreeNode;
int find(char* arr, int start, int end, char key) {
for (int i = start; i <= end; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
pTreeNode buildTree(char* preorder, char* inorder, int inStart, int inEnd) {
static int preIndex = 0;
if (inStart > inEnd) {
return NULL;
}
pTreeNode newNode = (pTreeNode)malloc(sizeof(TreeNode));
newNode->data = preorder[preIndex++];
if (inStart == inEnd) {
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int inIndex = find(inorder, inStart, inEnd, newNode->data);
newNode->left = buildTree(preorder, inorder, inStart, inIndex - 1);
newNode->right = buildTree(preorder, inorder, inIndex + 1, inEnd);
return newNode;
}
int getDepth(pTreeNode node) {
if (node == NULL) {
return 0;
}
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
void getSubNodeCount(pTreeNode node, int* countArr) {
if (node == NULL) {
return;
}
if (node->left != NULL) {
countArr[node->data - 'A']++;
getSubNodeCount(node->left, countArr);
}
if (node->right != NULL) {
countArr[node->data - 'A']++;
getSubNodeCount(node->right, countArr);
}
}
void levelOrderTraversal(pTreeNode root) {
if (root == NULL) {
return;
}
pTreeNode queue[MAX_SIZE];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
pTreeNode node = queue[front++];
printf("%c ", node->data);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
printf("\n");
}
int main() {
int length;
printf("请输入二叉树的长度:");
scanf("%d", &length);
// 读入先序序列和中序序列
char preorder[MAX_SIZE], inorder[MAX_SIZE];
printf("请输入先序序列:");
scanf("%s", preorder);
printf("请输入中序序列:");
scanf("%s", inorder);
// 构建二叉树
pTreeNode root = buildTree(preorder, inorder, 0, length - 1);
// 输出层序遍历结果
printf("层序遍历结果为:");
levelOrderTraversal(root);
// 计算节点个数及其每个节点的子节点个数
int depth = getDepth(root);
int nodeCount = 0;
int subNodeCount[MAX_SIZE] = { 0 };
for (int i = 0; i < length; i++) {
if (preorder[i] >= 'A' && preorder[i] <= 'Z') {
nodeCount++;
}
}
getSubNodeCount(root, subNodeCount);
// 输出结果
printf("节点个数为:%d\n", nodeCount);
printf("每个节点的子节点个数为:");
for (int i = 0; i < nodeCount; i++) {
printf("%d ", subNodeCount[i]);
}
printf("\n");
return 0;
}
```
这段代码使用递归的方式构建二叉树,并且使用队列实现了层序遍历。同时,还计算了二叉树的节点个数及其每个节点的子节点个数。注意,在输入序列时,我假定了节点的名称为大写字母,如果不是大写字母,需要修改代码。
阅读全文