题目
对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 “-”。编号间以 1 个空格分隔。
输出格式:
在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
结尾无空行
输出样例:
4 1 5
结尾无空行
思路
程序分为两部分,一部分是构造二叉树,另一部分是遍历二叉树输出叶子结点。
构造二叉树前,需要先找到根节点。由样例可以推出,根节点就是输入数据没有出现的元素,所以设flag数组,用来寻找未出现的元素(即根节点)。对于样例的‘-’改成数字100,方便后续处理。
对于叶子结点的输出要求是先上后下,先左后右,满足二叉树的层次遍历的特点,就可以在层次遍历的代码中进行修改。增设cnt条件,控制空格的输出。
代码
#include <stdio.h>
#include <stdlib.h>
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;
}