对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
本题只要找出根节点,然后从根节点按照层序遍历写即可。其中读入用scanf返回值得特性能简单处理,层序用队列处理比较方便。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#define inf 2147483647
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rr read()
#define ll long long
#define repb(i,a,b) for(int i=a;i<=b;i++)
#define CloseIo ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
int read()
{
char ch = getchar();
int x = 0, f = 1;
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while('0' <= ch && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
struct node
{
int lchild,rchild;
node()
{
lchild=-1;
rchild=-1;
}
}z[100];
void ceng(int s)
{
queue<int>q;
q.push(s);
int flag=0;
while(!q.empty())
{
int i=q.front();
q.pop();
if(z[i].lchild!=-1)q.push(z[i].lchild);
if(z[i].rchild!=-1)q.push(z[i].rchild);
if(z[i].lchild==-1&&z[i].rchild==-1)
{
flag++;
if(flag!=1)printf(" ");
printf("%d",i);
}
}
}
int main()
{
int n=rr;
int f[105]={0};
rep(i,0,n)
{
rep(j,0,2)
{
int t;
if(scanf("%d",&t)==1)
{
if(j==0)
z[i].lchild=t;
else
z[i].rchild=t;
f[t]++;
}
}
}
rep(i,0,n)
{
if(!f[i])
{
cent(i);
break;
}
}
}