|
发表于 2023-4-17 23:23:37
|
显示全部楼层
本楼为最佳答案
 1、设计算法以输出每个结点到根结点之间的路径上的所有结点的值。
以下是一个C语言实现的递归算法,用于输出二叉树中每个结点到根结点之间的路径上的所有结点的值:
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct TreeNode {
- char val;
- struct TreeNode *left;
- struct TreeNode *right;
- } TreeNode;
- void printArray(char arr[], int n) {
- for (int i = 0; i < n; i++) {
- printf("%c -> ", arr[i]);
- }
- printf("根结点\n");
- }
- void printPathsRecur(TreeNode *node, char path[], int pathLen) {
- if (node == NULL) {
- return;
- }
- path[pathLen] = node->val;
- pathLen++;
- if (node->left == NULL && node->right == NULL) {
- printArray(path, pathLen);
- } else {
- printPathsRecur(node->left, path, pathLen);
- printPathsRecur(node->right, path, pathLen);
- }
- }
- void printPaths(TreeNode *node) {
- char path[1000];
- int pathLen = 0;
- printPathsRecur(node, path, pathLen);
- }
- int main() {
- // 创建一个简单的二叉树
- TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
- root->val = 'A';
- root->left = (TreeNode *)malloc(sizeof(TreeNode));
- root->left->val = 'B';
- root->left->left = NULL;
- root->left->right = NULL;
- root->right = (TreeNode *)malloc(sizeof(TreeNode));
- root->right->val = 'C';
- root->right->left = NULL;
- root->right->right = NULL;
- printPaths(root);
- return 0;
- }
复制代码
2、设计算法将一棵以顺序存储方式存储在数组A[]中的二叉树(已转换为完全二叉树,补充的虚拟结点为值为'#')转换为二叉链表存储形式。
以下是一个C语言实现的算法,用于将顺序存储的二叉树转换为链式存储的二叉树:
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct TreeNode {
- char val;
- struct TreeNode *left;
- struct TreeNode *right;
- } TreeNode;
- TreeNode *buildBinaryTree(const char A[], int index, int size) {
- if (index >= size || A[index] == '#') {
- return NULL;
- }
- TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
- node->val = A[index];
- node->left = buildBinaryTree(A, 2 * index + 1, size);
- node->right = buildBinaryTree(A, 2 * index + 2, size);
- return node;
- }
- void printPreOrder(TreeNode *node) {
- if (node == NULL) {
- return;
- }
- printf("%c ", node->val);
- printPreOrder(node->left);
- printPreOrder(node->right);
- }
- int main() {
- char A[] = {'A', 'B', 'C', 'D', '#', 'E', 'F'};
- int size = sizeof(A) / sizeof(char);
- TreeNode *root = buildBinaryTree(A, 0, size);
- printf("前序遍历链式存储的二叉树:\n");
- printPreOrder(root);
- printf("\n");
- return 0;
- }
复制代码
这个代码首先实现了一个名为`buildBinaryTree`的递归函数,它根据给定的顺序存储二叉树数组和当前索引创建一个新的二叉树结点,然后递归创建左子树和右子树。当遇到虚拟结点(值为`#`)时,返回NULL。函数`printPreOrder`则用于输出链式存储二叉树的前序遍历结果。
在`main`函数中,首先创建一个顺序存储的二叉树数组`A`,然后调用`buildBinaryTree`函数将数组转换为链式存储的二叉树。最后,使用`printPreOrder`函数输出链式存储二叉树的前序遍历结果。
|
|