1. 程式人生 > >資料結構 筆記:二叉樹結構的層次遍歷

資料結構 筆記:二叉樹結構的層次遍歷

二叉樹的遍歷

-二叉樹的遍歷(Traversing Binay Tree)是指從根節點觸發,按照某種次序一次訪問二叉樹中的所有結點,使得每個結點被訪問一次,且僅被訪問一次。

通用樹結構的層次遍歷演算法是否可以用在二叉樹結構上?

如果可以,程式碼需要做怎樣的改動?

提供一組遍歷相關的函式,按層次訪問二叉樹中的資料元素。

函式 功能說明
begin() 初始化,準備進行遍歷訪問
next() 移動遊標,指向下一個結點
current() 獲取遊標所指向的資料元素
end() 判斷遊標是否到達尾部

層次遍歷演算法

-原諒:class LinkQueue<T>;

-遊標:LInkQueue<T>::front();

-思想:

·begin() -> 將根節點壓入佇列中

·current()->訪問隊頭元素指向的資料元素

·next()->隊頭元素彈出,將隊頭元素的孩子壓入佇列中(核心)

·end()->判斷佇列是否為空

層次遍歷演算法示例

函式呼叫 佇列狀態 出隊結點
begin() 1  
next() 2,3 1
next() 4,5,6,7 3
next() 5,6,7,8,9 4
next() 6,7,8,9,10 5
next() 7,8,9,10 6
next() 8,9,10 7
next() 9,10 8
... ... ...
bool begin()
    {
        bool ret = (root()!= NULL);

        if(ret)
        {
            m_queue.clear();
            m_queue.add(root());
        }

        return ret;
    }

    bool end()
    {
        return (m_queue.length() == 0);
    }

    bool next()
    {
        bool ret = (m_queue.length() > 0);

        if(ret)
        {
            BTreeNode<T>* node = m_queue.front();

            m_queue.remove();

            if(node->left != NULL)
            {
                m_queue.add(node->left);
            }

            if(node->right != NULL)
            {
                m_queue.add(node->right);
            }
        }

        return ret;
    }

    T current()
    {
        if(!end())
        {
            return m_queue.front()->value;
        }
        else
        {
            //丟擲異常
        }
    }

for(bt.begin();!bt.end();bt.next())
    {
        cout << bt.current() << " ";
    }