03-树2 List Leaves (25分)
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 N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N 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:
Sample Output:
4 1 5
叶子结点查找输出思路:将原有的二叉树转换成为一个新的完全二叉树,并在新二叉树中保存原二叉树的结点位置。利用完全二叉树的特点,即第i个结点,其左子树为2i,右子树为2i+1,进行判断是否为叶子结点。
代码:
#include <stdio.h>
#define maxsize 100
#define Tree int
struct TreeNode {
int left;
int right;
}T[maxsize];
void LevelOrder (struct TreeNode T[], int R, int N);
int BuildTree (struct TreeNode T[], int N);
int main () {
int R, N;
scanf ("%d", &N);
getchar();
R = BuildTree(T, N); //建立树并返回根节点位置
LevelOrder (T, R, N) ;
return 0;
}
int BuildTree (struct TreeNode T[], int N) {//读取输入的数据
int i, root = -1;
char cl, cr;
int check [maxsize];
if (N) {
for (i = 0; i < N; i++) {
check[i] = 0;
}
for (i = 0; i < N; i++) {
scanf ("%c %c", &cl, &cr);
getchar();
if (cl != '-') {
T[i].left = cl - '0';
check[T[i].left] = 1;
}
else T[i].left = -1;
if (cr != '-') {
T[i].right = cr - '0';
check[T[i].right] = 1;
}
else T[i].right = -1;
}
for (i = 0; i < N; i++) {
if(!check[i]) break;
}
root = i;
}
return root;
}
void LevelOrder (struct TreeNode T[], int R, int N) {//查找叶子结点
int i, j;
int idx = 0; //用于判断当前打印的是否为第一个结点
if (R != -1) {
int Q[maxsize];
for (i = 0; i < maxsize; i++) {//利用Q来保存新的树,-1代表该结点为空
Q[i] = -1;
}
Q[1] = R;//将根结点存入数组当中,从1开始
for (i = 1, j = 0; j < N; i++) {//i为当前查找的结点编号,j为有数据的结点个数
if (Q[i] != -1) { //当前结点不空时,在该结点对应的左右子树位置放入原树的结点编号
Q[2*i] = T[Q[i]].left;
Q[2*i+1] = T[Q[i]].right;
if (Q[2*i] == -1 && Q[2*i+1] == -1) { //当前第i个结点的左右均为空时,说明为叶子结点,输出
if (idx) printf(" ");
idx = 1;
printf ("%d", Q[i]);
}
j++;//每查找到一个有数据的结点,结点数+1
}
}
}
}