树的重构【东北大学oj数据结构7-4】C++

题面

编写一个程序,分别读取二叉树上前序树遍历和中序树遍历得到的两个节点序列,并在二叉树上打印后序树遍历得到的节点序列。

输入

第一行给出了一个整数 n,它是二叉树中的节点数。(1≤n≤40)

在第二行中,通过前序树遍历获得的节点 ID 序列以空格字符分隔给出。

在第二行中,通过中序树遍历获得的节点 ID 序列以空格字符分隔给出。

每个节点都有一个从 1 到 n 的唯一 ID。 请注意,根并不总是对应于 1。

输出

将后序树遍历获得的节点 ID 序列打印成一行。 在相邻 ID 之间放置一个空格字符。

输入样例

5

1 2 3 4 5

3 2 4 1 5

输出样例

3 4 2 5 1

cpp 复制代码
#include <iostream>
#include <stack>
#include <vector>
#include <unordered_map>
using namespace std;

#define MAX 41

// 定义树的节点结构
struct Node {
    int p, l, r;
};

struct Node T[MAX];  // 树节点数组
int n;  // 节点的数量
unordered_map<int,int> m;

int buildtree(int po[],int ps,int pe,int io[],int is,int ie)
{
    if(ps>pe||is>ie)
        return -1;
    int rootval=po[ps];
    int rootidx=m[rootval];
    int leftsize=rootidx-is;
    T[rootval].p=-1;
    T[rootval].l=buildtree(po,ps+1,ps+leftsize,io,is,rootidx-1);
    T[rootval].r=buildtree(po,ps+leftsize+1,pe,io,rootidx+1,ie);
    if(T[rootval].l!=-1)
        T[T[rootval].l].p=rootval;
    if(T[rootval].r!=-1)
        T[T[rootval].r].p=rootval;

    return rootval;
}

void posorder(int root)
{
    if(root==-1) return;
    stack<int> s1,s2;
    s1.push(root);
    while(!s1.empty())
    {
        int node=s1.top();
        s1.pop();
        s2.push(node);
        if(T[node].l!=-1)
            s1.push(T[node].l);
        if(T[node].r!=-1)
            s1.push(T[node].r);
    }
    while(!s2.empty())
    {
        cout<<s2.top()<<" ";
        s2.pop();
    }
}

int main() {
    int v;
    int a[41],b[41];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        T[i].p = T[i].l = T[i].r = -1;
    }
    for (int i = 0; i < n; i++) {
        scanf("%d", &v);
        a[i]=v;
    }
    for (int i = 0; i < n; i++) {
        scanf("%d", &v);
        b[i]=v;
        m[v]=i;
    }
    int root=buildtree(a,0,n-1,b,0,n-1);
    posorder(root);
    return 0;
}
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码3 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎