03-树1. List Leaves
题意:先输入总节点数N,之后N行数据代表第i行的左右儿子,输出所有树叶的编号,从上到下,从左到右。
/* ***********************************************
Author :xryz
Email :523689985@qq.com
Created Time :3-29 19:56:01
File Name :\Users\xryz\Desktop\0301.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct node//结点
{
int leftchild;
int rightchild;
node()
{
leftchild=-1;
rightchild=-1;
}
};
node n[20];
bool r[20];//寻找跟结点
queue<int>q;//队列储存
bool f;//控制输出
void fun(int x)
{
q.push(x);
while(!q.empty())//队列不为空
{
int j=q.front();//取队首
q.pop();//放弃队首
//printf(" %d\n",j);
if(n[j].leftchild==-1&&n[j].rightchild==-1)//叶结点
{
if(!f) {printf("%d",j);f++;}
else printf(" %d",j);
}
if(n[j].leftchild!=-1)
{
q.push(n[j].leftchild);
}
if(n[j].rightchild!=-1)
{
q.push(n[j].rightchild);
}
}
}
int main()
{
char a,b;
int m,i;
while(~scanf("%d",&m))
{
f=0;
memset(r,0,sizeof(r));
for(i=0;i<m;i++)
{
cin>>a>>b;
if(a>='0'&&a<='9')
{
n[i].leftchild=a-'0';
r[a-48]=true;
}
if(b>='0'&&b<='9')
{
n[i].rightchild=b-'0';
r[b-48]=true;
}
//printf("%c%c\n",a,b);
}
for(i=0;i<m;i++)
{
//printf("%d\n",i);
if(r[i]==0)
{
fun(i);
//printf("% d\n",i);
break;
}
}
printf("\n");
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/