劉汝佳書–p102

來源:互聯網
上載者:User

//測試範例:
//(3,l) (4,r) ()
//(11,ll) (7,l) (8,lll) (7,l) (7,) ()
//(11,ll) (7,lll) (4,l) (5,) ()
//(11,ll) (7,l) (8,lll) (7,) ()
//(11,ll) (8,lll) (7,) ()
//(11,ll) (7,lll) (8,r) (5,) (4,l) (13,rl) (2,llr) (1,rrr) (4,rr) ()

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
const int N=20;
char str[20],c[10];
int a[1<<N];
struct NODE
{
    int v,value;
    struct NODE *l,*r;
    NODE()
    {
        r=l=NULL;
        value=0;
    }
};
NODE *root;
int v;
NODE *newnode()
{
    return new NODE;//不能用malloc,只申請記憶體,不調用建構函式!!
}
int addnode(int v,char c[])
{
    int i=0;
    NODE *p=root;
    while(c[i])
    {
        if(c[i]=='l')
        {
            if(p->l==NULL)
                p->l=newnode();
            p=p->l;

        }
        else if(c[i]=='r')
        {
            if(p->r==NULL)
                p->r=newnode();
            p=p->r;
        }
        i++;
    }
    if(p->value==1)
    {
        return 0;
    }
    p->value=1;
    p->v=v;
    return 1;
}

int  input()
{
    root=newnode();
    int flag=0;
    while(1)
    {
        if(scanf("%s",str)!=1)
            return 0;
        if(!strcmp(str,"()"))
            break;
        sscanf(str,"(%d,%s",&v,c);//使用sscanf函數
        if(!addnode(v,c))
        {
            flag=1;
        }
    }
    if(flag)
    {
        return 2;
    }
    return 1;
}
NODE *q[N];
int dfs()
{
    int l=0,r=1;
    q[0]=root;
    NODE *p;
    while(l<r)
    {
        p=q[l++];
        if(p->l!=NULL)
            q[r++]=p->l;
        if(p->r!=NULL)
            q[r++]=p->r;
        if(p->value==0)
            return 0;
    }
    for(int i=0; i<r; i++)
        cout<<q[i]->v<<" ";
    cout<<endl;
    return 1;
}
int main()
{
    freopen("ex.in","r",stdin);
    int flag=0;
    while((flag=input()))
    {
        if(flag==2)
            cout<<-1<<endl;//<<"chongfu"
        else if(!dfs())
            cout<<-1<<endl;//<<"wu zhi!"

    }

    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.