1086 再次树遍历

发布时间 2023-04-21 23:12:32作者: 回忆、少年

通过使用栈可以以非递归方式实现二叉树的中序遍历。

例如,假设遍历一个如下图所示的 6 节点的二叉树(节点编号从 1 到 6)。

则堆栈操作为:push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop()。

我们可以从此操作序列中生成唯一的二叉树。

你的任务是给出这棵树的后序遍历。

3.png

输入格式

第一行包含整数 N,表示树中节点个数。

树中节点编号从 1 到 N

接下来 2N 行,每行包含一个栈操作,格式为:

  • Push X,将编号为 X 的节点压入栈中。
  • Pop,弹出栈顶元素。

输出格式

输出这个二叉树的后序遍历序列。

数据保证有解,数和数之间用空格隔开,末尾不能有多余空格。

数据范围

1N30

输入样例:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

输出样例:

3 4 2 6 5 1

代码实现:

#include<iostream>
#include<stack>
#include<vector>
#include<unordered_map>
using namespace std;
const int N=55;
stack<int>s1;
vector<int>v;
int pre[N],middle[N],idx,idx1,l[N],r[N];
unordered_map<int,int>mp;
int buildTree(int l1,int r1,int l2,int r2){
    if(l1>r1||l2>r2)return 0;
    int t=pre[l2];
    int k=mp[t];
    if(l1<k)l[t]=buildTree(l1,k-1,l2+1,l2+k-l1);
    if(r1>k)r[t]=buildTree(k+1,r1,l2+k-l1+1,r2);
    return t;
}
void dfs(int x){
    if(x==0)return;
    dfs(l[x]);
    dfs(r[x]);
    v.push_back(x);
}
int main(){
    int n;
    cin>>n;
    for(int i=0;i<2*n;i++){
        string s;
        cin>>s;
        if(s=="Push"){
            int x;
            cin>>x;
            s1.push(x);
            pre[idx++]=x;
        }else{
            middle[idx1++]=s1.top();
            mp[s1.top()]=idx1-1;
            s1.pop();
        }
    }
    int root=buildTree(0,n-1,0,n-1);
    dfs(root);
    for(int i=0;i<v.size();i++){
        if(i==0)cout<<v[i];
        else cout<<" "<<v[i];
    }
    return 0;
}