一、队列
- typedef int Position;
- struct QNode {
- ElementType *Data; /* 存储元素的数组 */
- Position Front, Rear; /* 队列的头、尾指针 */
- int MaxSize; /* 队列最大容量 */
- };
- typedef struct QNode *Queue;
- Queue CreateQueue( int MaxSize )
- {
- Queue Q = (Queue)malloc(sizeof(struct QNode));
- Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
- Q->Front = Q->Rear = 0;
- Q->MaxSize = MaxSize;
- return Q;
- }
- bool IsFull( Queue Q )
- {
- return ((Q->Rear+1)%Q->MaxSize == Q->Front);
- }
- bool AddQ( Queue Q, ElementType X )
- {
- if ( IsFull(Q) ) {
- printf("队列满");
- return false;
- }
- else {
- Q->Rear = (Q->Rear+1)%Q->MaxSize;
- Q->Data[Q->Rear] = X;
- return true;
- }
- }
- bool IsEmpty( Queue Q )
- {
- return (Q->Front == Q->Rear);
- }
- ElementType DeleteQ( Queue Q )
- {
- if ( IsEmpty(Q) ) {
- printf("队列空");
- return ERROR;
- }
- else {
- Q->Front =(Q->Front+1)%Q->MaxSize;
- return Q->Data[Q->Front];
- }
- }
二、二叉树
typedef struct Tree *binTree;
typedef binTree Position;
struct Tree{
ElementType Date;
binTree Left;
binTree Right;
}
/*先序*/
void PreorderTraversal(binTree BT){
printf("%d",BT->Date);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
/*中序*/
void InorderTraversal(binTree BT){
InorderTraversal(BT->Left);
printf("%d",BT->Date);
InorderTraversal(BT->Right);
}
/*后序*/
void PostorderTraversal(binTree BT){
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf("%d",BT->Date);
}
/*非递归中序*/
void InorderTraversal(binTree BT){
binTree T=BT;
Stack S=CreateStack(MaxSize);
while(T||IsEmpty(S)){
while(T){
Push(S,T);
T=T->Left;
}
if(!IsEmpty(S)){
T=Pop(S);
printf("%5d",T->Date);
T=T->Right;
}
}
}
/*非递归先序*/
void InorderTraversal(binTree BT){
binTree T=BT;
Stack S=CreateStack(MaxSize);
while(T||IsEmpty(S)){
while(T){
Push(S,T);
printf("%5d",T->Date);
T=T->Left;
}
if(!IsEmpty(S)){
T=Pop(S);
T=T->Right;
}
}
}
- void LevelorderTraversal ( BinTree BT )
- {
- Queue Q;
- BinTree T;
- if ( !BT ) return; /* 若是空树则直接返回 */
- Q = CreatQueue(); /* 创建空队列Q */
- AddQ( Q, BT );
- while ( !IsEmpty(Q) ) {
- T = DeleteQ( Q );
- printf("%d ", T->Data); /* 访问取出队列的结点 */
- if ( T->Left ) AddQ( Q, T->Left );
- if ( T->Right ) AddQ( Q, T->Right );
- }
- }