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.
输入格式:
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.
输出格式:
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.
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
4 1 5
思路:
- 建树-结构体数组
- 存储-返回树的根结点
- 层序遍历-队列实现
代码:
#include <stdio.h>
#include <stdlib.h>
#define maxSize 10
#define Null -1
/*建树结构体*/
struct Tree{
int left;
int right;
}T[maxSize];
/*队列结构体*/
struct TreeQueue {
int *data;
int rear;
int front;
};
typedef struct TreeQueue *Queue;
int creatTree(struct Tree T[]);
void LevelOrderTraversal(int root);
Queue CreateQueue();
void Add(Queue s, int item);
int Delete(Queue s);
int main() {
int r;
/*传入树所在的地址,返回树的根结点地址*/
r = creatTree(T);
/*层序遍历*/
LevelOrderTraversal(r);
return 0;
}
/*建树,返回根结点下标*/
int n;
int creatTree(struct Tree T[]) {
int check[maxSize];
char cl, cr;
scanf_s("%d", &n);
if (n < 0 || n>11) return Null;
/*初始化每一个结点-无父结点*/
for (int i = 0; i < n; i++) check[i] = 0;
/*筛选后赋值*/
for (int i = 0; i < n; i++) {
getchar();
scanf_s("%c %c", &cl,1, &cr,1);
if (cl == '-') {
T[i].left = Null;
}
else{
T[i].left = cl-'0';
check[T[i].left] = 1;
}
if (cr == '-') {
T[i].right = Null;
}
else {
T[i].right = cr-'0';
check[T[i].right] = 1;
}
}
/*循环找出根结点下标*/
for (int i = 0; i < n; i++) {
if (!check[i]) {
return i;
}
}
return Null;
}
/*层序遍历-队列实现*/
void LevelOrderTraversal(int root) {
Queue s;
int t=root, count=0;
if (t == -1) return;
s = CreateQueue();
Add(s,t);
while (!IsEmpty(s)){
count++;
t = Delete(s);
if (T[t].left != -1 && T[t].right == -1) {
Add(s, T[t].left);
}
else if (T[t].left == -1 && T[t].right != -1) {
Add(s, T[t].right);
}
else if (T[t].left != -1 && T[t].right != -1) {
Add(s, T[t].left);
Add(s, T[t].right);
}
else {
if (count != n) {
printf("%d ", t);
}
else {
printf("%d", t);
}
}
}
}
/*生成空队列*/
Queue CreateQueue() {
Queue s = (Queue)malloc(sizeof(struct TreeQueue));
s->data = (int *)malloc(maxSize * sizeof(int));//堆栈的顺序存储实现
s->front = -1;
s->rear = -1;
return s;
}
/*判断队列是否为空*/
int IsEmpty(Queue s) {
if (s->front == s->rear) {
return 1;
}
else {
return 0;
}
}
/*元素item入队列*/
void Add(Queue s, int item) {
if ((s->rear+1)%maxSize==s->front) {
return;
}
else {
s->rear = (s->rear + 1) % maxSize;
s->data[s->rear] = item;
return;
}
}
/*删除队列元素*/
int Delete(Queue s) {
if (s->front == s->rear) {
return;
}
else {
s->front = (s->front+1) % maxSize;
return s->data[s->front];
}
}