【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;
}    
相关推荐
草莓熊Lotso1 小时前
【数据结构初阶】--双向链表(二)
c语言·数据结构·经验分享·链表·刷题
西猫雷婶1 小时前
python学智能算法(二十三)|SVM-几何距离
开发语言·人工智能·python·算法·机器学习·支持向量机
用户8685016008612 小时前
想要训练语音模型,如何从影视剧音频中获取到纯净的语音数据?
算法
WebGoC开发者2 小时前
C++题解(37) 信息学奥赛一本通1318:【例5.3】自然数的拆分
c++·算法·青少年编程·题解
Aurora_wmroy2 小时前
算法竞赛备赛——【图论】求最短路径——小结
数据结构·c++·算法·蓝桥杯·图论
우리帅杰3 小时前
【python数据结构&算法篇】基本介绍
数据结构·python·算法
<但凡.4 小时前
数据结构与算法之美:拓扑排序
数据结构·算法·深度优先
拾光拾趣录4 小时前
举一反三:删除排序数组重复项
前端·算法
遇见尚硅谷4 小时前
C语言:20250719笔记
c语言·开发语言·数据结构·c++·算法
mit6.8244 小时前
7.17 滑动窗口 |assign |memo |pii bfs |位运算
c++·算法