###### 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 NN (\le 10≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1N−1. Then NN 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

#include <iostream>
#include <queue>
using namespace std;

//#define Elementtype int
#define null -1
typedef struct Bintree
{
//Elementtype data;
int left;
int right;
}Bintree;
Bintree* bintree;
int treenum ;
int* flag;
void input()
{

cin >> treenum;

bintree = new Bintree[treenum];
flag = new int[treenum];

char temp = 0;
for (int i = 0; i < treenum; i++)
{
cin >> temp;
if (temp == '-')
{
bintree[i].left = -1;
}
else
{
bintree[i].left = temp - '0';
flag[bintree[i].left] = 1;
}

cin >> temp;
if (temp == '-')
{
bintree[i].right = -1;
}
else
{
bintree[i].right = temp - '0';
flag[bintree[i].right] = 1;
}

}
delete[]bintree;
delete[]flag;
}

int findtop()
{
for (int i = 0; i < treenum; i++)
{

if (flag[i] != 1)
return i;
}
}

void traverse()
{
int top = findtop();

queue<int> q;
q.push(top);

while (!q.empty())
{
top = q.front();
q.pop();

if (bintree[top].left != null)
{
q.push(bintree[top].left);
}
if (bintree[top].right != null)
{
q.push(bintree[top].right);
}
if (bintree[top].left == null&&bintree[top].right == null)
{
if (!q.empty())
cout << top << ' ';
else
cout << top;
}
}

}

int main()
{
input();
traverse();

return 0;
}

#### 03-树2. List Leaves(25)

2015-06-27 22:38:59

#### PAT - 03-树2 List Leaves (25分)

2016-09-21 12:43:55

#### 03-树2 List Leaves (25分)

2015-10-19 19:02:02

#### 03-树2. List Leaves (25) Python C

2015-08-19 14:22:23

#### 03-树2. List Leaves (25)

2015-07-20 22:33:27

#### pat 03-树2 List Leaves（mooc 陈越、何钦铭-数据结构）

2016-09-19 20:48:44

#### 03-2. List Leaves (25)

2014-12-18 20:25:36

#### PAT 03-2. List Leaves (25)

2015-01-05 20:19:30

#### 03-树2 List Leaves (25分) (查找叶子节点)

2016-11-25 18:42:31

#### 中国大学MOOC-陈越、何钦铭-数据结构-2017秋 03-树2 List Leaves（25 point(s)）

2017-10-21 16:57:16

## 不良信息举报

03-树2 List Leaves