UVA122

本題的基本思路就是先建樹,然後在遍歷二叉樹,用線性表把數據存起來。

劉汝佳書中提到c語言字符串的靈活性,即把“指向字符的指針”看成字符串,下面的sscanf(&s[1],"%d",&v)中&s[1]即從s[1]開始的字符串。代碼實現應該並不困難。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1000;
int ans[MAXN],flot,k,v;
bool failed;
struct Node
{
    bool h_v;
    int v;
    Node *L,*R;
    Node():h_v(false),L(NULL),R(NULL) {}
}*head;//定義節點
void addnode(int v,char *s)
{
    Node *cur=head;
    for(int i=0;s[i];i++)
    {
        if(s[i]=='L')
        {
         	if(cur->L==NULL) cur->L=new Node();
         	cur=cur->L;
        }
        if(s[i]=='R')
        {
            if(cur->R==NULL) cur->R=new Node();
            cur=cur->R; 
        }
    }
    if(cur->h_v) failed=true;
    cur->v=v;
    cur->h_v=true;
}
void print()
{
    queue<Node *>q;
    Node *cur=head;
    q.push(head);
    while(!q.empty())
    {
        cur=q.front();
        q.pop();
        if(!cur->h_v) flot=0;
        if(!flot) break;
        ans[k++]=cur->v;
        if(cur->L!=NULL) q.push(cur->L);
        if(cur->R!=NULL) q.push(cur->R);
    }
    if(!failed&&flot)
    {
        for(int i=0;i<k;i++)
        {
        if(i) printf(" ");
        cout<<ans[i];
        }
    }
    else
    printf("not complete");
    puts("");
}
void freenode(Node *cur)
{
    if(cur==NULL) return ;
    freenode(cur->L);
    freenode(cur->R);
    free(cur);
}
int main()
{
    char s[MAXN];
    failed=false;
    head=new Node();
    while(~scanf("%s",s))
    {
        if(strcmp(s,"()")==0)
        {
            flot=1;
            k=0;
            print();
            freenode(head);
            head=new Node();
            failed=false;
            continue;
        }
        sscanf(&s[1],"%d",&v);
        addnode(v,strchr(s,',')+1);
    }
    return 0;
}

 

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