#include <stdio.h> #include <stdlib.h> #define MAX_N 100 typedef struct TreeNode { char val; struct TreeNode *left; struct TreeNode *right; } TreeNode; int findIdx(char *arr, int start, int end, char val) { for (int i = start; i <= end; i++) { if (arr[i] == val) { return i; } } return -1; } TreeNode *buildTree(char *preorder, char *inorder, int start, int end) { static int preIdx = 0; if (start > end) { return NULL; } TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = preorder[preIdx++]; if (start == end) { node->left = NULL; node->right = NULL; return node; } int inIdx = findIdx(inorder, start, end, node->val); node->left = buildTree(preorder, inorder, start, inIdx - 1); node->right = buildTree(preorder, inorder, inIdx + 1, end); return node; } int getNodeCount(TreeNode *root) { if (root == NULL) { return 0; } return getNodeCount(root->left) + getNodeCount(root->right) + 1; } void printLevelOrder(TreeNode *root) { if (root == NULL) { return; } TreeNode *queue[MAX_N]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { int levelSize = rear - front; for (int i = 0; i < levelSize; i++) { TreeNode *node = queue[front++]; printf("%c ", node->val); if (node->left) { queue[rear++] = node->left; } if (node->right) { queue[rear++] = node->right; } } printf("\n"); } } int getChildCount(TreeNode *node) { if (!node || (!node->left && !node->right)) { return 0; } int count = 0; if (node->left) { count++; } if (node->right) { count++; } return count; } int main() { char preorder[MAX_N], inorder[MAX_N], target; int n, len; printf("请输入二叉树长度、先序序列、中序序列:\n"); scanf("%d%s%s", &n, preorder, inorder); len = strlen(preorder); TreeNode *root = buildTree(preorder, inorder, 0, len - 1); printf("层序遍历:\n"); printLevelOrder(root); printf("节点个数为:%d\n", getNodeCount(root)); printf("请输入要查询子节点的节点:\n"); scanf(" %c", &target); TreeNode *node = root; while (node && node->val != target) { if (node->val > target) { node = node->left; } else { node = node->right; } } if (!node) { printf("未找到该节点!\n"); } else { printf("子节点个数为:%d\n", getChildCount(node)); } return 0; }
时间: 2024-04-05 22:34:29 浏览: 90
#include <stdio.h>
4星 · 用户满意度95%
这段代码是一段用 C 语言写的二叉树的操作程序。它实现了二叉树的构建、节点数量的统计、层序遍历、以及查询某个节点的子节点数量。其中,buildTree 函数用先序遍历和中序遍历序列构建二叉树,getNodeCount 函数用递归的方式统计二叉树的节点数量,printLevelOrder 函数用队列实现二叉树的层序遍历,getChildCount 函数用来查询某个节点的子节点数量。这段程序还包含了一些输入输出的操作,例如读入二叉树的长度和先序、中序序列,以及输出层序遍历结果和节点数量。
阅读全文