您的位置:首页 > 其它

树 List Leaves 【用数组模拟了树状结构建树+搜索叶子节点+按照特殊规律输出每个叶子节点】

2015-09-16 16:30 441 查看
Givenatree,youaresupposedtolistalltheleavesintheorderoftopdown,andlefttoright.

InputSpecification:

Eachinputfilecontainsonetestcase.Foreachcase,thefirstlinegivesapositiveintegerN(≤10)whichisthetotalnumberofnodesinthetree--andhencethenodesarenumberedfrom0toN−1.ThenNlinesfollow,eachcorrespondstoanode,andgivestheindicesoftheleftandrightchildrenofthenode.Ifthechilddoesnotexist,a"-"willbeputattheposition.Anypairofchildrenareseparatedbyaspace.

OutputSpecification:

Foreachtestcase,printinonelinealltheleaves'indicesintheorderoftopdown,andlefttoright.Theremustbeexactlyonespacebetweenanyadjacentnumbers,andnoextraspaceattheendoftheline.

SampleInput:

8
1-
--
0-
27
--
--
5-
46

SampleOutput:

415

分析:数据量很小,怎么写都过啊。于是我用结构体数组来模拟建立树状结构。然后找到每个叶子节点,但输出有要求。先输出深度小的节点,深度相同的叶子节点
先输出靠左的叶子节点,再输出靠右的叶子节点。


样例建树后的样子
[/code]

#include<stdio.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #include<queue> #include<algorithm> usingnamespacestd; structnode { intll; intrr; intdata; intdep; intdfn; }q[20]; structN { intnum; intdep; intdfn; booloperator<(constN&dd)const{ if(dep==dd.dep) returndd.dfn<dfn; else returndd.dep<dep; } }; intcnt; voiddfs_leaf(introot,intdeep) { if(q[root].ll==-1&&q[root].rr==-1) return; if(q[root].ll!=-1){ intv=q[root].ll; q[v].dep=deep+1; q[v].dfn=cnt++; dfs_leaf(v,deep+1); } if(q[root].rr!=-1){ intv=q[root].rr; q[v].dep=deep+1; q[v].dfn=cnt++; dfs_leaf(v,deep+1); } } intmain() { intn;scanf("%d%*c",&n); inti,j,k; chara[5],b[5]; for(i=0;i<n;i++){ scanf("%s%s",a,b); if(a[0]=='-'){ q[i].ll=-1; }else{ q[i].ll=a[0]-48; } if(b[0]=='-'){ q[i].rr=-1; }else{ q[i].rr=b[0]-48; }//模拟每一个树节点 }//建树完成 boolf[20];//标记每一个节点是不是儿子 memset(f,false,sizeof(f)); for(i=0;i<n;i++){ if(q[i].ll!=-1){ f[q[i].ll]=true; } if(q[i].rr!=-1){ f[q[i].rr]=true; } } introot; for(i=0;i<n;i++){ if(f[i]==false){ root=i;break; } } //printf("root=%d\n",root); cnt=1; q[root].dfn=0;q[root].dep=0; dfs_leaf(root,0); priority_queue<N>que; Ncur; for(i=0;i<n;i++){ if(q[i].ll==-1&&q[i].rr==-1){ cur.num=i; cur.dep=q[i].dep; cur.dfn=q[i].dfn; que.push(cur); //printf("%d节点:深度%d次序%d\n",i,q[i].dep,q[i].dfn); } } boolz=false; while(!que.empty()){ if(z==false){ printf("%d",que.top().num);z=true;que.pop(); } else{ printf("%d",que.top().num);que.pop(); } }printf("\n"); return0; }


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: