1086 Tree Traversals Again (25 分)

参考(color{green}{yls})代码,虽然自己思路大体上相同,但离代码实现还差一步,菜的安详>_<。

思路

题意其实就是下面的伪代码:

void inorder(int root)
{
    if(root == 0) return;
    push(root);
    inorder(tree[root].lchild);
    pop();
    inorder(tree[root].rchild);
}

现在给定你出栈入栈的序列(类似DFS序),还原出树,其实就是根据给定的序列反向模拟了。

代码

type=0表示下一个待插入的为左孩子结点,type=1表示下一个待插入的为右孩子结点。

const int N=35;
PII tree[N];
vector<int> post;
int n;

void postorder(int root)
{
    if(root == 0) return;
    postorder(tree[root].fi);
    postorder(tree[root].se);
    post.pb(root);
}

int main()
{
    cin>>n;

    int root;
    int fa=0;
    int type=0;
    stack<int> stk;
    for(int i=0;i<n*2;i++)
    {
        string s;
        cin>>s;
        if(s == "Push")
        {
            int x;
            cin>>x;
            stk.push(x);
            if(fa == 0) root=x;
            else
            {
                if(type == 0) tree[fa].fi=x;
                else tree[fa].se=x;
            }
            type=0;
            fa=x;
        }
        else
        {
            fa=stk.top();
            stk.pop();
            type=1;
        }
    }

    postorder(root);

    for(int i=0;i<post.size();i++)
        if(i) cout<<' '<<post[i];
        else cout<<post[i];
    cout<<endl;
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14448959.html