数据结构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];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值