數據結構——二叉樹的層次遍歷

二叉樹的層次遍歷說簡單也簡單,說難也難。下面是我讀編程之美和研究數據結構結合大神的博客來實現的二叉樹的層次遍歷,這裏只給出三種簡單高效的解法。

數據結構

typedef char datatype;
typedef struct bintreenode
{
    datatype data;
    struct bintreenode* lchild,*rchild;
}bintree;

方法一

採用廣度優先遍歷的思想,利用隊列實現二叉樹的層次遍歷。

void levelorder(bintree* t)
{
    queue<bintree*> que;
    bintree* p;
    if(t)
        que.push(t);
    do 
    {
        p = que.front();
        que.pop();
        cout << p->data << " ";
        if (p->lchild)
            que.push(p->lchild);
        if (p->rchild)
            que.push(p->rchild);
    } while (!que.empty());
}

方法二

有時需要分層遍歷二叉樹,這時比較好的解法是在入隊列的時候在每層的末尾添加一個標識符。具體解法如下

//插入一個空指針表示一層的結束
void levelorder3(bintree* t)
{
    queue<bintree*> que;
    bintree* p;
    que.push(t);
    que.push();

    while(!que.empty())
    {
        p = que.front();
        que.pop(0);
        if (p)
        {
            cout << p->data << "  ";
            if (p->lchild)
                que.push(p->lchild);
            if (p->rchild)
                que.push(p->rchild);
        }
        else if (!que.empty())
        {
            que.push(0);
            cout << endl;
        }
    }
}

方法三

這個方法是我自己實現的,不使用STL中的隊列,而是自己建立一個隊列來實現。

void levelorder(bintree* t)
{
    //建立循環隊列,能滿足7層的滿二叉樹遍歷
    const int maxsize = 64;
    bintree* queue[maxsize]; 
    int front,rear;
    //利用隊列實現層次遍歷
    /*front 指向最先進入的元素,rear指向隊尾(待插入的元素位置),不考慮隊列滿的情況(rear+1)%maxsize = front*/
    front = 0;rear = 1;
    queue[0] = t;  //根結點插入
    bintree* p;
    while(front != rear)
    {
        p = queue[front];
        front = (front+1)%maxsize;
        printf("%c",p->data);
        //上面出了一次隊列,所以不用檢查隊列滿的情況。
        if (p->lchild != NULL)
        {
            queue[rear] = p->lchild;
            rear = (rear+1)%maxsize;
        }
        if (p->rchild != NULL && (rear+1)%maxsize != front)
        { 
        //(rear+1)%maxsize != front,檢查防止隊列滿的情況。
            queue[rear] = p->rchild;
            rear = (rear+1)%maxsize;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章