# 7-1 列出叶结点（25 分） 【数据结构】

7-1 列出叶结点（25 分）

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

4 1 5

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-30;

const int INF = 0x3f3f3f3f;
const int maxn = 1e2 + 5;
const int MOD = 1e9 + 7;

int v[10];

struct Node
{
int l, r;
}q[10];

void init()
{
CLR(q);
CLR(v);
}

queue <int> Q;
vector <int> ans;

void bfs()
{
int len = Q.size();
for (int i = 0; i < len; i++)
{
int num = Q.front();
Q.pop();
if (q[num].l == -1 && q[num].r == -1)
ans.pb(num);
if (q[num].l != -1)
Q.push(q[num].l);
if (q[num].r != -1)
Q.push(q[num].r);
}
if (Q.size())
bfs();
}

int main()
{
init();
int n;
scanf("%d", &n);
char a, b;
for (int i = 0; i < n; i++)
{
scanf(" %c %c", &a, &b);
if (a == '-')
q[i].l = -1;
else
{
q[i].l = a - '0';
v[a - '0'] = 1;
}
if (b == '-')
q[i].r = -1;
else
{
q[i].r = b - '0';
v[b - '0'] = 1;
}
}
int root;
for (int i = 0; i < n; i++)
{
if (v[i] == 0)
{
root = i;
break;
}
}
Q.push(root);
bfs();
vector <int>::iterator it;
for (it = ans.begin(); it != ans.end(); it++)
{
if (it != ans.begin())
printf(" ");
printf("%d", *it);
}
cout << endl;
}