PTA数据结构之 List Leaves

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 N1. 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


解题思路:就是给你一颗树,让你按从上到下,从左往右的顺序输出叶子结点的序号;
代码如下:
 1 #include<iostream>
 2 using namespace std;
 3 
 4 int n ;
 5 bool vis[15];
 6 struct node{
 7     int lchild;    //定义一个左孩子 
 8     int rchild;    //定义一个右孩子; 
 9 }tree[15];       //定义一个树的结构体; 
10 int sz[15];      //后面用来存树的信息; 
11 int head = 0 , rear = 0;       //后面方便输出叶子结点的序号; 
12 int main()
13 {
14     cin>>n;
15     char l , r;
16     for(int i = 0 ; i < n ;i++)
17     {
18         cin>>l>>r;
19         if(l!='-')    //如果为数字; 
20         {
21             tree[i].lchild = l - '0';  //将其转化为数字;因为我们输入的是字符 
22             vis[tree[i].lchild] = 1;     //并标记这个数字我们已访问过 ,是i的左的孩子; 
23         }else
24         {
25             tree[i].lchild = -1;    //否则i没有左孩子,将其置为-1; 
26         }
27     
28         if(r!='-')           //为右孩子,原理同上; 
29         {
30             tree[i].rchild = r - '0';
31             vis[tree[i].rchild] = 1;
32         }else
33         {
34             tree[i].rchild = -1;
35         }
36     }
37     int root;
38         for(int i = 0 ; i < n ;i++)
39     {
40          if(vis[i]==0)      //如果i都不是谁的孩子,没有被访问过,则它是根结点; 
41          {
42              root = i ;
43              break;
44          }
45     }
46     int leaves = 0;
47      sz[rear++] = root;
48      while(rear - head > 0 )
49     {
50         int num = sz[head++];
51         if (tree[num].lchild == -1 && tree[num].rchild == -1) {    //输出叶节点,既没左孩子也没右孩子; 
52 
53             if (leaves)       
54 
55                 printf(" ");    //输出格式; 
56 
57             printf("%d", num);
58 
59             ++leaves;   //若是叶子结点,则叶子结点数目++; 
60 
61         }
62 
63         if (tree[num].lchild != -1) {        //如果存在,左孩子入队
64 
65             sz[rear++] = tree[num].lchild;
66 
67         }
68 
69         if (tree[num].rchild != -1) {        //如果存在,右孩子入队
70 
71             sz[rear++] = tree[num].rchild;
72 
73         }
74 
75         
76      }     
77     return 0 ;
78 }

猜你喜欢

转载自www.cnblogs.com/yewanting/p/10714358.html