二叉树的层序遍历线性实现-带输入输出-实验
运行效果:
在这里插入代码片
/* 完整代码 */
//层序遍历线式实现
#include<bits/stdc++.h>
#define MaxSize 100
typedef struct tree{
int data;
struct tree *left;
struct tree *right;
}TNode,*TList;
typedef struct Queue{
TList a[MaxSize];
int rear;
int front;
}Queue;
void InitQueue(Queue &Q){
Q.front=Q.rear=0;
}
void push(Queue &Q,TList t){
Q.a[++Q.rear]=t;
}
TList Pop(Queue &Q){
return Q.a[++Q.front];
}
bool isEmpty(Queue &Q){
return Q.front==Q.rear;
}
TList creatTree(TList root){
int value;
scanf("%d",&value);
if(value==-1) return NULL;
root=(TList)malloc(sizeof(TList));
root->data=value;
printf("请输入%d的左子树:",root->data);
root->left=creatTree(root->left);
printf("请输入%d的右子树:",root->data);
root->right=creatTree(root->right);
return root;
}
void LevelOrderTraversal (Queue &Q,TList root){
TList temp;
push(Q,root);
while(!isEmpty(Q)){
temp=Pop(Q);
printf("%d ", temp->data);
if(temp->left) push(Q,temp->left);
if(temp->right) push(Q,temp->right);
}
}
int main(){
Queue Q;
InitQueue(Q);
printf("请输入头节点:");
TList root = creatTree(root);
LevelOrderTraversal(Q,root);
putchar('\n');
return 0;
}