1086 Tree Traversals Again (25 分)一般 / 建树 树的遍历

Posted 辉小歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1086 Tree Traversals Again (25 分)一般 / 建树 树的遍历相关的知识,希望对你有一定的参考价值。


https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024
首先要知道的是:

  • 入栈顺序就是树的前序遍历的顺序
  • 出栈顺序就是树的中序遍历的顺序

故问题,就转换成了根据前序遍历,中序遍历的顺序建树的过程。
最后遍历树输出后序遍历的结果即可。

#include<bits/stdc++.h>
using namespace std;
vector<int>a,b,ans;
stack<int>st;
int n;
unordered_map<int,int>L,R,S;
int build(int l1,int r1,int l2,int r2)
{
    auto root=a[l1];
    int k=S[root];//找到中序遍历所对应的位置。
    if(k>l2) L[root]=build(l1+1,l1+k-l2,l2,k-1);
    if(k<r2) R[root]=build(l1+k-l2+1,r1,k+1,r2);
    return root;
}
void dfs(int root)
{
    if(L.count(root)) dfs(L[root]);//有左儿子
    if(R.count(root)) dfs(R[root]);//有右儿子
    ans.push_back(root);
}
int main(void)
{
    cin>>n;
    for(int i=0;i<n*2;i++)
    {
        string op; cin>>op;
        if(op=="Push")
        {
            int x; cin>>x;
            a.push_back(x);
            st.push(x);
        }else
        {
            int u=st.top(); st.pop();
            b.push_back(u);
        }
    }
    for(int i=0;i<b.size();i++) S[b[i]]=i;
    build(0,n-1,0,n-1);//建树
    dfs(a[0]);//遍历树
    for(int i=0;i<ans.size();i++) 
    {
        if(i) cout<<" ";
        cout<<ans[i];
    }
    return 0;
}

以上是关于1086 Tree Traversals Again (25 分)一般 / 建树 树的遍历的主要内容,如果未能解决你的问题,请参考以下文章