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 (<=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.

1
2
3
4
5
6
7
8
9
10
11
12
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct BinNode
{
char val;
BinNode *left, *right;
};

void search(vector<char> svec1, vector<char> svec2, char fNode, char &lNode, char &rNode)
{

int position = fNode - '0';
lNode = svec1[position];
rNode = svec2[position];
}

BinNode *createTree(vector<char> &svec1, vector<char> &svec2, char fNode)
{

char lNode, rNode;
search(svec1, svec2, fNode, lNode, rNode);
BinNode *bn = new BinNode;
if(fNode != '-')
{
bn->val = fNode;
bn->left = createTree(svec1,svec2, lNode);
bn->right = createTree(svec1, svec2, rNode);
}
else
{
bn = NULL;
}
return bn;
}

void levelOrderTraversal(BinNode *bn)
{

if(bn == NULL)
{
return;
}
string str;
int countNum = 0;
BinNode *Quene[10], *tmp;
int rear = -1, front = -1;
Quene[++rear] = bn;
while(rear != front)
{
tmp = Quene[++front];
if(tmp->left == NULL && tmp->right == NULL)
{
if(countNum == 0)
{
cout << tmp->val;
++countNum;
}
else
{
cout << " " << tmp->val;
}
}
if(tmp->left != NULL)
{
Quene[++rear] = tmp->left;
}
if(tmp->right != NULL)
{
Quene[++rear] = tmp->right;
}
}
}
int main()
{

string str("0123456789"), input;
int N = 0;
cin >> N;
vector<char> svec1, svec2;
for(int i = 0; i < N; ++i)
{
char ch1, ch2;
cin >> ch1 >> ch2;
svec1.push_back(ch1);
svec2.push_back(ch2);
if(ch1 != '-')
{
input += ch1;
}
if(ch2 != '-')
{
input += ch2;
}
}
if(N != 0)
{
int position = 0;
char rootNode;
if((position = str.find_first_not_of(input)) != string::npos)
{
rootNode = '0' + position;
}
BinNode *root;
root = createTree(svec1, svec2, rootNode);
levelOrderTraversal(root);
}
cout <<endl;
return 0;
}

本题我的思路是:
1.先找根节点
2.根据根节点来创建树
3.层次遍历

网上有大牛的代码更短,并没有创建树,但是模拟了树的层次遍历。