1. 程式人生 > >PTA 資料結構與演算法題目集(中文)6-9

PTA 資料結構與演算法題目集(中文)6-9

void InorderTraversal( BinTree BT ) {   BinTree stack[50];   int top=-1;   BinTree p=BT;   while(p!=NULL||top!=-1)   {     while(p)     {       stack[++top]=p;       p=p->Left;     }     if(top!=-1)     {       p=stack[top--];       printf(" %c",p->Data);       p=p->Right;     }   }  } void PreorderTraversal( BinTree BT ) {   BinTree stack[50];   int top=-1;   BinTree p=BT;   while(p!=NULL||top!=-1)   {     while(p)     {       printf(" %c",p->Data);       stack[++top]=p;       p=p->Left;     }     if(top!=-1)     {       p=stack[top--];       p=p->Right;     }   } } typedef struct node  {   BinTree ptr;   int flag; }stacknode; void PostorderTraversal( BinTree BT ) {   stacknode stack[50];   int top=-1;   BinTree p=BT;   while(p!=NULL||top!=-1)   {     while(p)     {       stack[++top].ptr=p;       stack[top].flag=1;       p=p->Left;     }     while(top!=-1&&stack[top].flag==2)     {       p=stack[top--].ptr;       printf(" %c",p->Data);       p=NULL;//特別注意!不加這句會陷入死迴圈!列印完一個節點要將其設定為空,避免再次訪問!     }     if(top!=-1)     {       stack[top].flag=2;       p=stack[top].ptr->Right;     }   } } void LevelorderTraversal( BinTree BT ) {   int maxsize=20;   BinTree queue[maxsize];   int front=0;   int rear=0;   if(BT)   {     rear=(rear+1)%maxsize;//使用迴圈陣列,下同     queue[rear]=BT;     while(rear!=front)     {       front=(front+1)%maxsize;       BinTree p=queue[front];       printf(" %c",p->Data);       if(p->Left)       {         rear=(rear+1)%maxsize;         queue[rear]=p->Left;       }       if(p->Right)       {         rear=(rear+1)%maxsize;         queue[rear]=p->Right;       }     }   } }