【PTA数据结构 | C语言版】根据后序和中序遍历输出前序遍历

本专栏持续输出数据结构题目集,欢迎订阅。

文章目录

题目

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的前序遍历结果。

输入格式:

第一行给出正整数 n (≤30),是树中结点的个数。随后两行,每行给出 n 个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。

输出格式:

在一行中输出Preorder: 以及该树的前序遍历结果。数字间有1个空格,行末不得有多余空格。

输入样例:

7

2 3 1 5 7 6 4

1 2 3 4 5 6 7

输出样例:

Preorder: 4 1 3 2 6 5 7

代码

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

#define MAX_N 30

int postorder[MAX_N], inorder[MAX_N];
int first_output = 1; // 标记是否是第一个输出的节点

// 根据后序和中序递归构建二叉树并输出前序遍历
void buildAndPrintPre(int post_start, int post_end, int in_start, int in_end) {
    if (post_start > post_end || in_start > in_end) return;
    
    // 后序遍历的最后一个元素是根节点
    int root_val = postorder[post_end];
    
    // 控制输出格式
    if (first_output) {
        printf("Preorder: %d", root_val);
        first_output = 0;
    } else {
        printf(" %d", root_val);
    }
    
    // 在中序遍历中找到根节点的位置
    int root_pos = in_start;
    while (inorder[root_pos] != root_val) root_pos++;
    
    // 计算左子树的节点数
    int left_count = root_pos - in_start;
    
    // 递归处理左子树
    buildAndPrintPre(post_start, post_start + left_count - 1, in_start, root_pos - 1);
    // 递归处理右子树
    buildAndPrintPre(post_start + left_count, post_end - 1, root_pos + 1, in_end);
}

int main() {
    int n;
    scanf("%d", &n);
    
    // 读取后序遍历
    for (int i = 0; i < n; i++) {
        scanf("%d", &postorder[i]);
    }
    
    // 读取中序遍历
    for (int i = 0; i < n; i++) {
        scanf("%d", &inorder[i]);
    }
    
    // 构建并输出前序遍历
    buildAndPrintPre(0, n - 1, 0, n - 1);
    printf("\n");
    
    return 0;
}    
相关推荐
Lazyafei3 小时前
滑动窗口:扩张与收缩的动态区间
算法
FRing034 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
老歌老听老掉牙4 小时前
三个等价答案:遗传算法如何逼近 Branin 函数
c++·算法·ga
是main不是漫4 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法
老花眼猫5 小时前
C语言绘图方法:(24)鼓形缩放旋转
c语言·经验分享·青少年编程·课程设计
慧都产品智能化5 小时前
汽车软件年底自查:按安全影响排定缺陷整改顺序
c语言·c++·测试工具·单元测试·汽车·代码规范
geovindu5 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Zwawa5 小时前
USB 与有线接口:插上去之后,这条线上发生了什么
c语言·单片机·嵌入式
Navigator_Z6 小时前
LeetCode //C - 1328. Break a Palindrome
c语言·算法·leetcode
电科_银尘6 小时前
【大模型算法与工程 46】vLLM部署入门:模型服务、请求与运行观测
算法·vllm