原题:http://www.patest.cn/contests/mooc-ds2015spring/03-%E6%A0%911(List Leaves)
思路:用结构数组保存结点,下标对应结点数据值,结构中的两个变量left与right保存左右孩子在数组中的下标。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <string>
#include <queue>
using namespace std;
typedef struct node{
int left;
int right;
}BinTree;
void ListOrder(BinTree a[], int n, int t) //层序遍历
{
queue<int> q;
bool first = true;
if (t >= 0){
q.push(t);
}
while (!q.empty()){
int tmp = q.front();
if (a[tmp].left != -1) q.push(a[tmp].left);
if (a[tmp].right != -1) q.push(a[tmp].right);
if (a[tmp].left == -1 && a[tmp].right == -1) {
if (first){
printf("%d", tmp);
first = false;
}
else printf(" %d", tmp);
}
q.pop();
}
}
int main()
{
int n;
BinTree a[10];
int list[10] = { 0 }; //记录有指针指向的结点
char left, right;
scanf("%d%*c", &n);
for (int i = 0; i < n; ++i){
a[i].left = -1;
a[i].right = -1;
}
int k = 0;
int cnt = n; //注意保存n 下面还要用
while (cnt--){
scanf("%c %c%*c", &left, &right);
if (left != '-') {
a[k].left = left - '0'; ++list[left - '0'];
}
if (right != '-') {
a[k].right = right - '0'; ++list[right - '0'];
}
++k;
}
int t = 0; //寻找根结点 list[i]为0的就是根结点
for (int i = 0; i < n; ++i){
if (list[i] == 0){
t = i;
break;
}
}
ListOrder(a, n, t);
return 0;
}