03-树2 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

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 #include <cstdio>
3 #include <queue>
4 using namespace std;
5 #define OK 1
6 #define ERROR 0
7
8 #define MaxTree 10
9 #define Null -1        //区别于系统的NULL 0
10
11 typedef int Status;/* Status是函数的类型,其值是函数结果状态代码，如OK等 */
13
14 typedef struct TreeNode
15 {
16     int left;
17     int right;
18 } Tree;
19
20 Tree T[MaxTree];
21
22 int BulidTree(Tree T[])
23 {
24     int N, check[MaxTree], root = Null;    //root = Null 空树则返回Null
25     char cl, cr;        //左右孩子序号
26     scanf("%d\n",&N);
27     if(N) {
28         for(int i = 0; i < N; i++)
29             check[i] = 0;
30         for(int i = 0; i < N; i++) {
31             scanf("%c %c\n",&cl,&cr);
32             //找root
33             if(cl != '-') {
34                 T[i].left = cl - '0';
35                 check[T[i].left] = 1;    //不是根节点
36             }else {
37                 T[i].left = Null;
38             }
39             if(cr != '-') {
40                 T[i].right = cr - '0';
41                 check[T[i].right] = 1;    //不是根节点
42             }else {
43                 T[i].right = Null;
44             }
45         }
46
47         for(int i = 0; i < N; i++)        //check[]=0的为根节点
48             if(!check[i]) {
49                 root = i;
50                 break;
51             }
52     }
53     return root;
54 }
55
56 void isLeaves(int root)
57 {
58     queue<int> queue;
59     queue.push(root);
60     int flagSpace = 1;
61     while(!queue.empty()) {
62         int temp = queue.front();
63         queue.pop();    //pop()虽然会移除下一个元素，但是并不返回
64         if( (T[temp].left == Null) && (T[temp].right == Null) ) {    //该结点是叶子
65             if(flagSpace) {                //控制输出格式
66                 printf("%d", temp);
67                 flagSpace = 0;
68             }else {
69                 printf(" %d", temp);
70             }
71         }else {
72             if(T[temp].left != Null)         //不是叶子把它儿子push进队列
73                 queue.push(T[temp].left);
74             if(T[temp].right != Null)
75                 queue.push(T[temp].right);
76         }
77     }
78     printf("\n");
79 }
80 int main()
81 {
82     int root1;
83     root1 = BulidTree(T);
84     isLeaves(root1);
85     return 0;
86 }

 
posted on 2016-03-19 20:29  kuotian  阅读(495)  评论(0编辑  收藏  举报