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

#include <stdlib.h>
#include <stdio.h>
#define ElemType char
typedef 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="" />


你可能感兴趣的:(二叉树,遍历,非递归,层次遍历)