二叉樹的遞歸遍歷以及層次遍歷

#include <stdio.h>
#include <stdlib.h>

#define ERROR 0
#define OK 1

typedef char TElemType;
typedef int Status;


//二叉樹的二叉鏈表存儲表示
typedef struct BiTNode
 {
  TElemType data;
  struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

//定義鏈式隊列結點
typedef struct QNode
{
 BiTree Queuedata;
 struct QNode * next;
}QNode,* QueuePtr;
//定義鏈式隊列
typedef struct
{
 QueuePtr front;
 QueuePtr rear;
}LinkQueue;

//按照先序次序構造二叉樹
Status CreatBiTree(BiTree &T)
{char ch;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else
{
 if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
  return ERROR;
 T->data=ch;
 CreatBiTree(T->lchild);
 CreatBiTree(T->rchild);
}
return OK;
}
//遞歸先序遍歷二叉樹
Status PreOrder ( BiTree T )
{
 if ( T!=NULL)
 {
  printf("%c",T->data); 
  PreOrder ( T->lchild );
  PreOrder ( T->rchild );
 }
 return OK;
}

//遞歸中序遍歷二叉樹
Status InOrder ( BiTree T )
{
 if ( T!=NULL)
 {
  InOrder ( T->lchild );
  printf("%c",T->data);
  InOrder ( T->rchild );
 }
 return OK;
}

//遞歸後序遍歷二叉樹
Status LastOrder ( BiTree T )
{
 if (T!=NULL)
 {
  LastOrder( T->lchild );
  LastOrder( T->rchild );
  printf("%c",T->data);
 }
 return OK;
}

//初始化一個帶頭結點的隊列
Status InitQueue(LinkQueue &Q)
{
 Q.front=(QNode*)malloc(sizeof(QNode));
 if (!Q.front)
  return ERROR;
 Q.rear=Q.front;
  Q.front->next=NULL;
 return OK;
}

//入隊列
Status EnQueue(LinkQueue &Q,BiTree e)
{
 QueuePtr s=(QueuePtr)malloc(sizeof(QNode));
 if (!s)
return ERROR;
 s->Queuedata=e;
 s->next=NULL;
 Q.rear->next=s;
 Q.rear=s;
 return OK;

}
//出隊
int DelQueue(LinkQueue &Q, BiTree &e)
{
 char data1;
 QueuePtr s;
 s=Q.front->next;
 e=s->Queuedata;
    data1=e->data;
 Q.front->next=s->next;
 if(Q.rear==s)
  Q.rear=Q.front;
 free(s);
 
 return OK;
}
//隊列的判斷空操作
Status QueueEmpty(LinkQueue Q)
{
 
 if (Q.front->next==NULL)
    return OK;
 else return ERROR;
 
}
//按層次遍歷
Status LevelBiTree(BiTree T)
{
 LinkQueue Q;
 
 InitQueue(Q);
 BiTree p = T;        
 if (T == NULL) return ERROR;
 
 EnQueue(Q,p);
 
 while (!QueueEmpty(Q))     
 {   DelQueue(Q, p);
  printf("%C",p->data);
 
 if (p->lchild) 
  EnQueue(Q, p->lchild);
 if (p->rchild)  
  EnQueue(Q, p->rchild);
 }

return OK;
}

int main()
{BiTree T;
printf("按照先序次序輸入二叉樹中結點的值.\n");
CreatBiTree(T);
printf("先序遍歷二叉樹:");
PreOrder(T);printf("\n");
printf("中序遍歷二叉樹:");
InOrder(T);printf("\n");
printf("後序遍歷二叉樹:");
LastOrder(T);printf("\n");
printf("按層次遍歷二叉樹:");
LevelBiTree(T);printf("\n");
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章