03-ツリー1.List Leaves
5134 ワード
标题:まず総節点数Nを入力し、その後N行データはi行目の左右の息子を表し、すべての木の葉の番号を上から下へ、左から右へ出力する.
/* *********************************************** Author :xryz Email :[email protected] 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
",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
",a,b);
}
for(i=0;i<m;i++)
{
//printf("%d
",i);
if(r[i]==0)
{
fun(i);
//printf("% d
",i);
break;
}
}
printf("
");
}
return 0;
}