#include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef struct TreeNode{ int data; struct TreeNode *lchild,*rchild; }TreeNode,*Tree; typedef struct{ TreeNode* data[MaxSize]; int front; int rear; }Queue; void InitQueue(Queue &Q) { Q.front=Q.rear=0; } bool isEmpty(Queue Q) { if(Q.front==Q.rear) { return true; } else { return false; } } bool isFull(Queue Q) { if((Q.rear+1)%MaxSize==Q.front) { return true; } else { return false; } } bool EnQueue(Queue &Q,TreeNode* p) { if(isFull(Q)) { return false; } Q.data[Q.rear]=p; Q.rear=(Q.rear+1)%MaxSize; return true; } bool DeQueue(Queue &Q,TreeNode* &p) { if(isEmpty(Q)) { return false; } p=Q.data[Q.front]; Q.front=(Q.front+1)%MaxSize; return true; } //先序创建二叉树 void CreateTree(Tree &T) { int x; scanf("%d",&x); if(x==-1) { T=NULL; return; } else { T=(Tree)malloc(sizeof(TreeNode)); T->data=x; printf("输入%d的左结点:",x); CreateTree(T->lchild); printf("输入%d的右结点:",x); CreateTree(T->rchild); } } //层次遍历(利用队列) void LevelOrder(Tree T) { Queue Q; InitQueue(Q); TreeNode *p=T; EnQueue(Q,p); while(!isEmpty(Q)) { DeQueue(Q,p); printf("%d ",p->data); if(p->lchild!=NULL) { EnQueue(Q,p->lchild); } if(p->rchild!=NULL) { EnQueue(Q,p->rchild); } } } int main() { Tree T; CreateTree(T); LevelOrder(T); return 0; }
标签:遍历,TreeNode,层次,Queue,二叉树,front,return,data,rear From: https://www.cnblogs.com/simpleset/p/17627955.html