9.2 1086 Tree Traversals Again (25 分)(***)棧push確定先序,pop確定中序,健樹的時候沒有返回地址可以作對樣例

#include <cstdio>
#include <stack>
#include<iostream>
#include<string>
using namespace std;
int n,pre[35],in[35],idxp = 0,idxi=0;
struct node
{
    int data;
    node* lc;
    node* rc;
};

node* create(int pl,int pr,int il,int ir)
{
    if(pl > pr)
        return NULL;
    node* root = new node;
    root->data = pre[pl];
    int i;
    for(i = il;i<=ir;i++)
    {
        if(in[i] == pre[pl])
            break;
    }
    int num = i - il;
    root->lc = create(pl+1,pl+num,il,i-1);
    root->rc = create(pl+num+1,pr,i+1,ir);
    return root;//沒有return居然也能做對樣例。。。
}
int cou = 0;
void pos(node*root)
{
    if(root == NULL)
        return;
    pos(root->lc);
    pos(root->rc);
    cou++;
    printf("%d",root->data);
    if(cou<n)
        printf(" ");
}


int main()
{
    freopen("in.txt","r",stdin);
    stack<int>s;
    scanf("%d",&n);
    for(int i = 0;i<n*2;i++)
    {
        int temp;
        string str;
        cin>>str;
        if(str == "Push")
        {
            cin>>temp;
            pre[idxp++] = temp;
            s.push(temp);
        }
        else if(str == "Pop")
        {
            in[idxi++] = s.top();
            s.pop();
        }
    }
    pos(create(0,n-1,0,n-1));

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章