二叉树的层次非递归遍历运用队列

来源:互联网 发布:ncbi下载基因组数据 编辑:程序博客网 时间:2024/06/12 00:10
#include <stdlib.h>#include <stdio.h>#define ElemType chartypedef struct BiTNode *BiTree;struct BiTNode{    ElemType data;    BiTree lchild,rchild;};BiTree CreateBiTree(){    ElemType ch;    BiTree T;    scanf("%c",&ch);    if(ch=='#')T=NULL;    else{        T = (BiTree)malloc(sizeof *T);        T->data = ch;        T->lchild = CreateBiTree();        T->rchild = CreateBiTree();    }    return T;}typedef struct QUEUEnode* link;struct QUEUEnode{BiTree item ;link next;};static link head , tail;link NEW(BiTree item, link next){link x = (link) malloc(sizeof *x);x->item = item;x->next = next;return x;}void QUEUEinit(int maxN){head = NULL;}int QUEUEempty(){return head == NULL;} void  QUEUEput(BiTree item){if(head == NULL){head =(tail = NEW(item,head)) ;return;}tail->next = NEW(item,tail->next);tail = tail->next;}BiTree QUEUEget(){BiTree item = head->item;link t = head->next;free(head);head = t;return item;} void levelTraverse(BiTree T){QUEUEinit(40);QUEUEput(T);while(!QUEUEempty()){T = QUEUEget();printf("%c",T->data);if(T->lchild!=NULL)QUEUEput(T->lchild);if(T->rchild!=NULL)QUEUEput(T->rchild);}}main(){    BiTree T;    T = CreateBiTree(); //先序建立二叉树     levelTraverse(T);// DBA##C##FE##G##}
运行结果图
<img src="http://img.blog.csdn.net/20150813134456713?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


0 0
原创粉丝点击