树的重构【东北大学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;
}
相关推荐
秦少游在淮海1 小时前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5441 小时前
cpp自学 day2(—>运算符)
开发语言·c++
虾球xz1 小时前
CppCon 2015 学习:CLANG/C2 for Windows
开发语言·c++·windows·学习
CodeWithMe2 小时前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
SuperCandyXu3 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
lyh13443 小时前
【SpringBoot自动化部署方法】
数据结构
愈努力俞幸运3 小时前
c++ 头文件
开发语言·c++
~山有木兮4 小时前
C++设计模式 - 单例模式
c++·单例模式·设计模式
十五年专注C++开发4 小时前
CMake基础:gcc/g++编译选项详解
开发语言·c++·gcc·g++
MSTcheng.4 小时前
【数据结构】顺序表和链表详解(下)
数据结构·链表