7-8 List Leaves(25 point(s))
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:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5 code:只要解决了储存问题和树根的判断这个题就解决了
#include <stdio.h> #include <string.h> #include <stdlib.h> int pre[20];//记录每个节点的父亲节点是几号 struct node{ int l; int r; }tre[20];//用一个tre结构体数组表示树,tre[i]表示i为根节点时,l r是它的左右儿子,没有初始化为-1; int n; int main(){ int i; scanf("%d",&n); getchar(); for(i = 0; i < n; i++){//初始化 tre[i].l = -1; tre[i].r = -1; pre[i] = -1; } for(i = 0; i < n; i++){ char a[5]; gets(a);//每行输入i号节点的两个儿子,用字符串方便输入 if(a[0]>='0'&&a[0]<='9'){//如果第一个是数字 int lson = a[0]-'0';//转换成数字 pre[lson] = i;//左儿子的父亲记为i tre[i].l = lson;//i的左儿子记为lson } if(a[2]>='0'&&a[2]<='9'){//右儿子是数字 int rson = a[2]-'0';//转换成int pre[rson] = i;//父亲记为i tre[i].r = rson;//i号节点记录右儿子 } } int rt; for(i = 0; i < n; i++){ if(pre[i]==-1){//如果有个点没有父亲,即父亲数组的值是-1,说明这个点是树根节点 rt = i; break; } } //然后从树根开始搜索 int q[20];//数组模拟队列 int vis[20];//标记数组 int ans[20];//答案数组 memset(vis,0,sizeof(vis)); int head = 0,tail = 0; int cnt = 0; q[tail++] = rt; while(head<tail){//相当于层序遍历 int subtre = q[head]; // printf("%d ",subtre); if(tre[subtre].l==-1&&tre[subtre].r==-1){ ans[cnt++] = subtre;//如果没有左右儿子,说明是叶子,放入答案数组 } if(tre[subtre].l!=-1){//如果这个点有左儿子,并且没有访问过入队 q[tail++] = tre[subtre].l; } if(tre[subtre].r!=-1){//如果这个点有右儿子,并且没有访问过入队 q[tail++] = tre[subtre].r; } head++; } for(i = 0; i < cnt; i++){ if(i==0)printf("%d",ans[i]); else printf(" %d",ans[i]); } puts(""); return 0; }