树的层次遍历(c语言描述)

由于数据结构课本没有层次遍历算法,我自己写了一些,现推出如下:

 #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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值