1. 程式人生 > >Trees On the Level

Trees On the Level

tree %d memset 坑爹 code ++ \n ont -s

Trees On the Level


竟然還有 (,) () 這種東西!!!

#include <cstdio>
#include <cstring>
#include <cctype>
const int MAXN=256+1;
char s[MAXN];
struct Node {
    int val;
    bool have;
    Node *left,*right;
    Node(int v=0,Node* l=NULL,Node* r=NULL):val(v),left(l),right(r) {
        have=false;
    }
}*root,*q[MAXN];
int front=0,rear=0;
void printAns(Node* root,int ok) {
    if(ok==0) {
        printf("not complete\n");
        return;
    }
    front=rear=0;
    q[rear++]=root;
    while(front<rear) {
        Node *u=q[front++];
        if(u->have==false) {
            ok=0;
            break;
        }
        if(u->left!=NULL)q[rear++]=u->left;
        if(u->right!=NULL)q[rear++]=u->right;
    }
    if(ok==0) {
        printf("not complete\n");
        return;
    }
    front=0;
    printf("%d",q[front++]->val);
    while(front<rear)printf(" %d",q[front++]->val);
    printf("\n");
}
Node* newNode() {
    return new Node(0,NULL,NULL);
}
void insert(int val,char s[],int& ok) {
    Node *u=root;
    int m=strlen(s);
    for(int i=0; i<m; i++) {
        if(s[i]==‘L‘) {
            if(u->left==NULL)u->left=newNode();
            u=u->left;
        }
        if(s[i]==‘R‘) {
            if(u->right==NULL)u->right=newNode();
            u=u->right;
        }
    }
    if(u->have==true)ok=0;
    else {
        u->val=val;
        u->have=true;
    }
    return;
}
void del(Node* u) {
    if(u->left!=NULL)del(u->left);
    if(u->right!=NULL)del(u->right);
    delete u;
}
int main() {
    int ok=1,val=0;
    root=newNode();
    while(scanf("%s",s)==1) {
        if(!strcmp(s,"()")) {
            printAns(root,ok);
            ok=1;
            del(root);
            root=newNode();
            memset(s,0,sizeof(s));
            memset(q,0,sizeof(q));
        } else {
            if(!isdigit(s[1]))ok=0;
            else sscanf(s+1,"%d",&val);
            int pos=strchr(s,‘,‘)-s+1;
            insert(val,s+pos,ok);
        }
    }
    return 0;
}

2018 年 10 月 30 日,真是一個不幸的日子.

在這一天,我終於把這道題 A 掉了,反反復復提交了十多次,終於在今天,我明白了為什麽錯:

UVa 坑爹輸出格式!!!輸出文件的結尾必須有一個空行!!!

Trees On the Level