【树】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 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

思路:

  • 构造二叉树
  • 层序遍历,遇到没有儿子的叶结点输出
 1 // 7-3List Leaves.cpp : 
 2 #include <iostream>
 3 #include <queue>
 4 using namespace std;
 5 
 6 #define MAXSIZE 10
 7 #define Null -1
 8 
 9 struct  TreeNode
10 {
11     int data;
12     int left;
13     int right;
14 }T[MAXSIZE];
15 
16 //建树
17 int BuildTree() {
18     int n,root=Null;
19     int check[MAXSIZE] = { 0 };
20     char cl, cr;
21     cin >> n;
22     for (int i= 0; i < n; i++) {
23         T[i].data = i;
24         cin >> cl >> cr;
25         if (cl != '-') {
26             T[i].left = cl - '0';
27             check[cl - '0']++;
28         }
29         else
30             T[i].left = Null;
31         if (cr != '-') {
32             T[i].right= cr - '0';
33             check[cr - '0']++;
34         }
35         else
36             T[i].right = Null;
37     }
38     for (int i = 0; i < n; i++) {
39         if (check[i] == 0) {
40             root = i;
41             break;
42         }
43     }
44     return root;//root是根结点的data而不是根结点
45 }
46 
47 void LevelTraversal(int root) {
48     queue<struct TreeNode>q;
49     struct TreeNode t;
50     int tag = 0;
51     if (root == Null) {
52         return;//空树
53     }
54     q.push(T[root]);
55     while (!q.empty())
56     {
57         t = q.front();//得到队首元素
58         q.pop();//出栈
59         //判断是否是叶子结点
60         if (t.left == Null && t.right == Null) {
61             if (tag == 1)cout << " ";
62             cout << t.data;
63             tag = 1;
64         }
65         if (t.left!= Null)q.push(T[t.left]);//压入队首元素(而不是root)的左右儿子
66         if (t.right != Null)q.push(T[t.right]);
67     }
68 
69 }
70 
71 int main()
72 {
73     int R;
74     R = BuildTree();//建立一棵树并返回根结点下标
75     LevelTraversal(R);
76     return 0;
77 }

 

posted @ 2020-03-29 17:12  PennyXia  阅读(118)  评论(0编辑  收藏  举报