List Leaves
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.
在这里插入代码片
#include<stdio.h>
#include<stdlib.h>
#define maxsize 10
struct Tree{
int left;
int right;
}t[maxsize];
typedef struct Queue{
int front;
int data[maxsize];
int rear;
}queue;
int creattree(struct Tree *a,int n);
void printleaf(int r,int n);
void creatqueue(queue *q);
int isqempty(queue *q);
void addq(queue *q,int elem);
int deleteq(queue *q);
int main(){
int n,r1;
scanf("%d",&n);
r1 = creattree(t,n);
printleaf(r1,n);
}
int isqempty(queue *q){
if(q->front==q->rear){
return 1;
}
else{
return 0;
}
}
void addq(queue *q,int elem){
if((q->rear+1)%maxsize==q->front){
printf("Queue is full");
}
else{
q->rear = (q->rear+1)%maxsize;
q->data[q->rear] = elem;
}
}
int deleteq(queue *q){
if(isqempty(q)){
printf("Queue is empty");
return;
}
else{
q->front = (q->front+1)%maxsize;
return q->data[q->front];
}
}
int creattree(struct Tree *a,int n){
int cheak[n];
int root = -1;
for(int i = 0;i<n;i++){
char cl,cr;
scanf(" %c %c",&cl,&cr);
if(cl!='-'){
a[i].left = cl-'0';
cheak[a[i].left] = 1;
}
else{
a[i].left = -1;
}
if(cr!='-'){
a[i].right = cr-'0';
cheak[a[i].right] = 1;
}
else{
a[i].right = -1;
}
}
for(int i = 0;i<n;i++){
if(cheak[i]==0){
root = i;
break;
}
}
return root;
}
void printleaf(int r,int n){
queue *q =(queue*)malloc(sizeof(queue));
q->front = 0;
q->rear =0;
addq(q,r);
while(!isqempty(q)){
int p = deleteq(q);
n--;
if(t[p].left==-1&&t[p].right==-1){
if(n){
printf("%d ",p);
}
else{
printf("%d",p);
}
}
if(t[p].left!=-1){
addq(q,t[p].left);
}
if(t[p].right!=-1){
addq(q,t[p].right);
}
}
}