1 题目描述
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
- Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.
- Output Specification:
For each test case, print in one line all the leaves’ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
- Sample Input:

- Sample Output:
4 1 5
2 解题思路
题意:按层次输出叶子节点
思路:由于数据都是小于10的整数,所以可以用数组存储二叉树,层次遍历二叉树则需要一个队列存储每一层的节点。遇到叶子节点就输出。
3 解决代码
#include<stdio.h>
struct node{ //数组用来存储二叉树
int data;
int left;
int right;
}tr[10];
int main()
{
int N,i,M=0;
int check[10]={0};
scanf("%d",&N);
getchar(); //读入换行符
for(i=0;i<N;i++){
char l,r;
scanf("%c %c",&l,&r); //读入左右孩子
getchar();
if(l=='-'&&r=='-')M++; //叶子节点个数
tr[i].data=i; //节点数据
tr[i].left=l=='-'?-1:l-'0';
tr[i].right=r=='-'?-1:r-'0';
if(l!='-')check[l-'0']=1; //查找根节点
if(r!='-')check[r-'0']=1;
}
int queue[10]={0},rear=-1,front=-1; //设置队列,按层次输出
struct node p;
for(i=0;i<N;i++) //根节点
{
if(check[i]==0)queue[++rear]=i; //队尾插入根节点
}
while(front!=rear){ //队列不为空
p=tr[queue[++front]]; //队头取出节点
if(p.left!=-1)queue[++rear]=p.left; //队尾插入左孩子
if(p.right!=-1)queue[++rear]=p.right; //队尾插入右孩子
if(p.left==-1&&p.right==-1){ //输出叶子节点
printf("%d",p.data);
M--;
if(M)printf(" ");
}
}
return 0;
}
4 提交结果
