HDU 1622 Trees On The Level

来源:互联网 发布:淘宝合约机预售啥意思 编辑:程序博客网 时间:2024/06/01 15:29

大水题,除了代码写起来很长、很烦之外没有难度了。给那些长时间不做OJ的人熟悉语言用的。

开头先建树,之后再BFS,结束之后不要忘记free一下就可以了[感觉没有free应该也没什么问题,毕竟空间太小了] 。

#include<stdio.h>#include<string.h>#include<stdlib.h>#define MAXN 256#define MAXS MAXN*20typedef struct node{int v;char vd;struct node *left;struct node *right;}tree;tree *newnode();char s[MAXN];tree *root;int fail;void addnode(int no,char *s);int main(){int no,i;int front,rear,num[MAXN+10];int finsh=0; tree *q[MAXN+10]; tree *now;while(!finsh){root=newnode();memset(s,0,sizeof(s)); fail=0;while(1){if(scanf("%s",s)==EOF){finsh=1;break;}if(strcmp(s,"()")==0)break; sscanf(s,"(%d",&no);addnode(no,strchr(s,',')+1);}if(finsh)break;if(fail)printf("not complete\n");else{front=1;rear=0;q[rear]=root;while(front>rear){now=q[rear];if(now->vd!=0)num[rear++]=now->v;elsebreak;if(now->left!=NULL)q[front++]=now->left;if(now->right!=NULL)q[front++]=now->right;}if(front>rear)printf("not complete\n");else{for(i=0;i<rear-1;i++)printf("%d ",num[i]);printf("%d\n",num[i]);}front=1;rear=0;q[rear]=root;while(front>rear){now=q[rear++];if(now->left!=NULL)q[front++]=now->left;if(now->right!=NULL)q[front++]=now->right;free(now);}}}return 0;}tree *newnode(){tree *p=(tree*)malloc(sizeof(tree));p->v=0;p->vd=0;p->left=NULL;p->right=NULL;return p;}void addnode(int no,char *s){int len=strlen(s)-1;int i;tree *c=root;for(i=0;i<len;i++){if(s[i]=='L'){if(c->left==NULL)c->left=newnode();c=c->left;}else{if(c->right==NULL)c->right=newnode();c=c->right;}}if(c->vd==1)fail=1;c->v=no;c->vd++;}


原创粉丝点击