题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3e3543ec876c7f926307a213fed4a476.png)
思路
- 数组存储二叉树结构
- 二叉树的层序遍历(用队列),遍历过程中输出叶子结点
代码
typedef struct TreeNode* BinTree;
typedef struct QNode* Queue;
struct TreeNode{
int left;
int right;
};
struct Node{
int data;
struct Node* next;
};
struct QNode{
struct Node* front;
struct Node* rear;
};
void Add(int data,Queue PtrQ)
{
struct Node* tmp;
tmp=(struct Node*)malloc(sizeof(struct Node));
tmp->data=data;
tmp->next=NULL;
if(PtrQ->front==NULL)
PtrQ->front=PtrQ->rear=tmp;
else{ PtrQ->rear->next=tmp;PtrQ->rear=tmp;}
}
int Delete(Queue PtrQ )
{
int data;
struct Node* firstcell;
firstcell=PtrQ->front;
if(PtrQ->front==PtrQ->rear)
PtrQ->front=PtrQ->rear=NULL;
else
PtrQ->front=PtrQ->front->next;
data=firstcell->data;
free(firstcell);
return data;
}
int plantTree(int N,struct TreeNode T[])
{
char left,right;
int flag=0;
for(int i=0;i<N;i++){
if(flag==1) scanf("\n");
else flag=1;
scanf("%c %c",&left,&right);
if(left=='-') T[i].left=-1;
else T[i].left=left-'0';
if(right=='-') T[i].right=-1;
else T[i].right=right-'0';
}
int root=0;
for(int i=0;i<N;i++){
if((T[i].left==root)||(T[i].right==root))
root=i; }
return root;
}
void PrintLeaves(int N,struct TreeNode T[],Queue Q)
{
int t;
int flag=0;
while(PtrQ->front!=NULL){
t=Delete(PtrQ);
if(T[t].left==-1&&T[t].right==-1){
if(flag==1) printf(" ");
else flag=1;
printf("%d",t);}
if(T[t].left!=-1) Add(T[t].left,PtrQ);
if(T[t].right!=-1) Add(T[t].right,PtrQ);
}
}
int main()
{
int N;
int root;
struct Node* s;
Queue PtrQ;
PtrQ=(Queue)malloc(sizeof(struct QNode));
scanf("%d\n",&N);
struct TreeNode T[N];
root=plantTree(N,T);
s=(struct Node*)malloc(sizeof(struct Node));
s->data=root;
s->next=NULL;
PtrQ->front=PtrQ->rear=s;
PrintLeaves(N,T,Q);
return 0;
}