数据结构PTA习题:03-树2 List Leaves (25分)

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:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

C语言程序代码:

#include <stdio.h>
#include<stdlib.h>
struct Node
{
 int data;
 int left;
 int right;
};
typedef struct Node * Bintree;
Bintree B;
struct Queue
{
 Bintree data;
 int front;
 int rear;
};
typedef struct Queue * queue;
queue Create();
void Add(struct Node n, queue Q);
struct Node Delete(queue Q);

int main()
{
 B = (Bintree)malloc(10 * sizeof(struct Node));
 struct Node t;
 int n;
 int flag = 0;
 scanf("%d\n", &n);
 int i;
 char l, r,c;
 int check[10]; //check数组用于寻找根结点,没有被指向的结点为根结点
 if (n)
 {
  for (i = 0; i < 10; i++)
  {
   check[i] = 0;
  }
  for (i = 0; i < n; i++)
  {
   B[i].data = i;
   scanf("%c", &l);
   if (l == '-') { B[i].left = -1; }
   else { B[i].left = l - '0'; check[B[i].left] = 1; }
   scanf("%c", &c);//字符c读入空格
   scanf("%c", &r);
   if (r == '-') { B[i].right = -1; }
   else { B[i].right = r - '0'; check[B[i].right] = 1; }
   scanf("%c", &c);
  }
  for (i = 0; i < n; i++)
  {
   if (check[i] == 0) { break; }
  }
  //通过层序遍历寻找叶结点
  queue Q;
  Q = Create();
  Add(B[i], Q);
  while (Q->front != Q->rear)
  {
   t = Delete(Q);
   if (t.left == -1 && t.right == -1)
   {
    if (flag == 0) { printf("%d", t.data); flag = 1; }
    else { printf(" %d", t.data); }
   }
   else {
    if (t.left != -1) { Add(B[t.left], Q); }
    if (t.right != -1) { Add(B[t.right], Q); }
   }
  }
 }
 return 0;
}

queue Create()
{
 queue Q;
 Q = (queue)malloc(sizeof(struct Queue));
 Q->data = (Bintree)malloc(10 * sizeof(struct Node));
 Q->front = -1;
 Q->rear = -1;
 return Q;
}

void Add(struct Node n, queue Q)
{
 Q->rear++;
 Q->data[Q->rear] = n;
}

struct Node Delete(queue Q)
{
 Q->front++;
 return Q->data[Q->front];
}
发布了21 篇原创文章 · 获赞 2 · 访问量 1634

猜你喜欢

转载自blog.csdn.net/wulila/article/details/105287619
今日推荐