数据结构学习 队列 二叉树

来源:互联网 发布:javascript动画 编辑:程序博客网 时间:2024/06/07 09:18

一、队列

  1. typedef int Position;
  2. struct QNode {
  3.     ElementType *Data;     /* 存储元素的数组 */
  4.     Position Front, Rear;  /* 队列的头、尾指针 */
  5.     int MaxSize;           /* 队列最大容量 */
  6. };
  7. typedef struct QNode *Queue;
  8.  
  9. Queue CreateQueue( int MaxSize )
  10. {
  11.     Queue Q = (Queue)malloc(sizeof(struct QNode));
  12.     Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
  13.     Q->Front = Q->Rear = 0;
  14.     Q->MaxSize = MaxSize;
  15.     return Q;
  16. }
  17.  
  18. bool IsFull( Queue Q )
  19. {
  20.     return ((Q->Rear+1)%Q->MaxSize == Q->Front);
  21. }
  22.  
  23. bool AddQ( Queue Q, ElementType X )
  24. {
  25.     if ( IsFull(Q) ) {
  26.         printf("队列满");
  27.         return false;
  28.     }
  29.     else {
  30.         Q->Rear = (Q->Rear+1)%Q->MaxSize;
  31.         Q->Data[Q->Rear] = X;
  32.         return true;
  33.     }
  34. }
  35.  
  36. bool IsEmpty( Queue Q )
  37. {
  38.     return (Q->Front == Q->Rear);
  39. }
  40.  
  41. ElementType DeleteQ( Queue Q )
  42. {
  43.     if ( IsEmpty(Q) ) { 
  44.         printf("队列空");
  45.         return ERROR;
  46.     }
  47.     else  {
  48.         Q->Front =(Q->Front+1)%Q->MaxSize;
  49.         return  Q->Data[Q->Front];
  50.     }
  51. }

二、二叉树

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

  1. void LevelorderTraversal ( BinTree BT )
  2.     Queue Q; 
  3.     BinTree T;
  4.  
  5.     if ( !BT ) return/* 若是空树则直接返回 */
  6.      
  7.     Q = CreatQueue(); /* 创建空队列Q */
  8.     AddQ( Q, BT );
  9.     while ( !IsEmpty(Q) ) {
  10.         T = DeleteQ( Q );
  11.         printf("%d ", T->Data); /* 访问取出队列的结点 */
  12.         if ( T->Left )   AddQ( Q, T->Left );
  13.         if ( T->Right )  AddQ( Q, T->Right );
  14.     }
  15. }

0 0