樹的層次遍歷(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);
}

發佈了25 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章