1. 程式人生 > >二叉樹---層次遍歷

二叉樹---層次遍歷

就是按層次來 首先是根節點A入佇列 然後是根節點的左B右C子樹 根節點A出佇列 左子B的左D右子樹入佇列然後B出佇列 C的左右子樹入對列C出佇列 然後是D以此迴圈知道佇列的頭部和尾部重合佇列空 輸出完畢

思路並不難,但是在網上看的寫的有點麻煩 照著一個ppt寫了個簡單一點的 可能不是最優的程式碼 但是很容易能理解這個思想和過程

#include<iostream>
#include<malloc.h>
#define LEN sizeof(BiTree)
#define MAXQSIZE   100;         //佇列長度
using namespace std;
struct BiTree                           //二叉樹
{
    char data;
    BiTree *lchild,*rchild;
}*T;
struct Qnode        //鏈佇列
{
    BiTree *Queue[100];   //M表示迴圈指標佇列的長度
     int nfront,nrear;        //頭和尾  用於處理陣列所以int就可以
}head;
BiTree* CreatBiTree()  //類似先序遍歷創立,空位置補*
{
    BiTree *T;
    char ch;cin>>ch;
    if(ch=='*')T=NULL;
    else{
        T=(BiTree *)malloc(LEN);
        T->data=ch;
        T->lchild=CreatBiTree();
        T->rchild=CreatBiTree();
     }
    return T;
}
void Levelorder(BiTree *T)
  {  BiTree *p;                                                                    // 建立一個 工作樹指標p
     Qnode Q;Q.nrear=Q.nfront=0;                                //初始化這個佇列
      if (T!=NULL)
        {   Q.Queue[Q.nrear]=T;                                         //如果T不空
       Q.nrear=(Q.nrear+1)%MAXQSIZE;              //加入一個尾尾部
        while (Q.nfront !=Q.nrear)                         //如果這個 佇列不空  也就是二叉樹不結束
            {
                  p=Q.Queue[Q.nfront];                                        //p等於佇列頭
       cout<<p->data;                                              //輸出佇列頭部
                 Q.nfront=(Q.nfront+1)%MAXQSIZE;           //front往後移動一個
                    if (p->lchild)                                                    //如果做左孩子不空
                { Q.Queue[Q.nrear]=p->lchild;                     //那麼尾部加上左孩子
                Q.nrear=(Q.nrear+1)%MAXQSIZE;                 //rear往後移動一個
                }
                if (p->rchild)                                              //然後是右孩子
                {  Q.Queue[Q.nrear]=p->rchild;             //同上
                Q.nrear=(Q.nrear+1)%MAXQSIZE;
                }
            }
        }
}

int main()                                                                   //執行 結束
{
    BiTree*test=CreatBiTree();
    Levelorder(test);
return 0;
}