#include<bits/stdc++.h>
using namespace std;
typedef struct TNode *Tree;
struct TNode
{
int data;
struct TNode *Left;
struct TNode *Right;
};
int flag[10]; //寻找根结点
struct Node
{
int left, right;
}num[10];
Tree Build(int node)
{
Tree t = (Tree) malloc(sizeof(struct TNode));
t->data = node;
t->Left = t->Right = NULL;
if(num[node].left != 100) t->Left = Build(num[node].left);
if(num[node].right != 100) t->Right = Build(num[node].right);
return t;
}
void Print(Tree T)
{
if(T == NULL) return;
Tree queue[10];
int left=0, right=0;
queue[right++] = T;
int cnt = 0; //计数,空格输出控制
while (left < right)
{
Tree t = queue[left++];
if(t->Left==NULL && t->Right==NULL) {
if(cnt == 0) printf("%d", t->data);
else printf(" %d", t->data);
cnt++;
}
if (t->Left) queue[right++] = t->Left;
if (t->Right) queue[right++] = t->Right;
}
}
int main()
{
int n;
scanf("%d", &n);
getchar();
for(int i=0; i<n; i++)
{
char x, y;
scanf("%c %c",&x, &y);
getchar();
if(x == '-') num[i].left = 100;
else
{
num[i].left = x - '0';
flag[x - '0'] = 1;
}
if(y == '-') num[i].right = 100;
else
{
num[i].right = y - '0';
flag[y - '0'] = 1;
}
}
int node;
for(int i=0; i<n; i++)
{
if(flag[i] == 0) node = i;
}
Tree t = Build(node);
Print(t);
return 0;
}
pta 7-6 列出叶结点
最新推荐文章于 2024-08-24 14:08:21 发布