层次遍历:即每一层从左向右输出
元素需要储存有先进先出的特性,所以选用队列存储。
队列的定义:
- #define MAX 1000
- typedef struct seqqueue{
- bintree data[MAX];
- int front;
- int rear;
- }seqqueue;
- void enter(seqqueue *q,bintree t){
- if(q->rear == MAX){
- printf("the queue is full!\n");
- }else{
- q->data[q->rear] = t;
- q->rear++;
- }
- }
- bintree del(seqqueue *q){
- if(q->front == q->rear){
- return NULL;
- }else{
- q->front++;
- return q->data[q->front-1];
- }
- }
遍历实现 :
- void level_tree(bintree t){
- seqqueue q;
- bintree temp;
- q.front = q.rear = 0;
- if(!t){
- printf("the tree is empty\n");
- return ;
- }
- enter(&q,t);
- while(q.front != q.rear){
- t=del(&q);
- printf("%c ",t->data);
- if(t->lchild){
- enter(&q,t->lchild);
- }
- if(t->rchild){
- enter(&q,t->rchild);
- }
- }
- }
时间: 2024-12-17 05:49:12