树 List Leaves 【用数组模拟了树状结构建树+搜索叶子节点+按照特殊规律输出每个叶子节点】
2015-09-16 16:30
441 查看
Givenatree,youaresupposedtolistalltheleavesintheorderoftopdown,andlefttoright.
分析:数据量很小,怎么写都过啊。于是我用结构体数组来模拟建立树状结构。然后找到每个叶子节点,但输出有要求。先输出深度小的节点,深度相同的叶子节点
先输出靠左的叶子节点,再输出靠右的叶子节点。
样例建树后的样子
[/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;
}
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]
相关文章推荐
- 【网络安全】Rop绕过DEP和ASRL流程实例介绍
- mysql5.6.26 源码安装(网络文章,待测试)
- asp.net验证码的简单制作
- 徐小明:低位杀跌并不可怕
- Goldengate 实现Oracle for Oracle 单向DDL操作同步
- WheelView省市县三级联动、单个滑轮效果以及各种效果
- python:PyInstaller打包发布单个文件错误struct.error: argument for 's' must be a string解决
- IOS开发之APP之间的相互通讯
- 网站首页的设计
- 大组合数:Lucas定理
- 利用Global 的BeginRequest事件实现域名的重写
- 查询所有sql执行时间
- Redhat6.5安装Docker
- 第三周项目2建设顺序表算法库
- hdu3072 Intelligence System(tarjan缩点+最小树形图)
- docker固定IP地址重启不变
- Dell笔记本不能安装XP或则2003的问题
- 例题6-5 移动盒子 UVa 12657 链表(模拟链表)
- HDU 4746 Mophues(莫比乌斯反演)
- HBase 数据模型