由于数据结构课本没有层次遍历算法,我自己写了一些,现推出如下:
#include<stdio.h>
typedef struct Tnode
{
char data;
struct Tnode *lchild;
struct Tnode *rchild;
}TNode,*TreeNode;
TreeNode creatTree(TreeNode T)
{
char ch=NULL;
ch=getchar();
if(ch!='#')
{
T=(TNode *)malloc(sizeof(TNode));
T->data=ch;
T->lchild=NULL;
T->rchild=NULL;
T->lchild=creatTree(T->lchild);
T->rchild=creatTree(T->rchild);
}
return T;
}
typedef struct Qnode
{
TreeNode data;
struct Qnode *next;
}QNode,*QueueNode;
typedef struct queue
{
QueueNode first;
QueueNode last;
}Queue,*QueueList;
QueueList InitQueue()
{
QueueList q=(Queue *)malloc(sizeof(Queue));
QueueNode qn=(QueueNode)malloc(sizeof(QNode));
q->first=qn;
q->last=qn;
return q;
}
void getQueue(QueueList q,TreeNode d)
{
QueueList p=q;
QueueNode Q=(QNode *)malloc(sizeof(QNode));
Q->data=NULL;
p->last->data=d;
p->last->next=Q;
p->last=Q;
}
TreeNode popQueue(QueueList q)
{
if(q->first!=q->last)
{
TreeNode tn=q->first->data;
q->first=q->first->next;
return tn;
}
else
{
return NULL;
}
}
QueueList ql;
void cengTree(TreeNode T)
{ if(T)
{
printf("%c",T->data);
if(T->lchild!=NULL)
getQueue(ql,T->lchild);
if(T->rchild!=NULL)
getQueue(ql,T->rchild);
T=popQueue(ql);
cengTree(T);
}
}
void main()
{
TreeNode s=NULL;
printf("Please input the TreeNode(if child is void input #):/n");
s=creatTree(s);
ql=InitQueue();
printf("ceng ci bian li binary tree:/n");
cengTree(s);
}