[編程之美-07]層序打印二元樹,每層打印一行

題目:輸入一顆二元樹,從上往下按層打印樹的每個結點,同一層中按照從左往右的順序打印。
例如輸入

  8
/  /

6 10
// //
5 7 9 11

輸出8 6 10 5 7 9 11
我們增加一下難度,我們打印如下的結果:
8
6 10
5 7 9 11
看到這裏大家已經知道我們是怎麼打印的吧。按行打印。

思想:層序遍歷的思想,就是引入last和nlast,last保存當前層最右一個節點,nlast保存下一行最右一個節點。

代碼如下:

#include<iostream>
#include<deque>
using namespace std;

struct BSTreeNode
{
    int m_nValue;
    BSTreeNode *m_pleft;
    BSTreeNode *m_pright;
};


void addBSTreeNode(BSTreeNode *&pCurrent, int value);

void levelOrderBSTree(BSTreeNode *pRoot);



int main()
{
    BSTreeNode *pRoot = NULL;

    addBSTreeNode(pRoot, 8);
    addBSTreeNode(pRoot, 6);
    addBSTreeNode(pRoot, 5);
    addBSTreeNode(pRoot, 7);
    addBSTreeNode(pRoot, 10);
    addBSTreeNode(pRoot, 9);
    addBSTreeNode(pRoot, 11);

    levelOrderBSTree(pRoot);

    return 0;
}


void levelOrderBSTree(BSTreeNode *pRoot)
{
    if(pRoot == NULL)
        return ;

    deque<BSTreeNode*> que;
    que.push_back(pRoot);

    BSTreeNode *last, *nlast;
    last = pRoot;
    nlast = pRoot;

    while(que.size() != 0)
    {
        BSTreeNode *pCurrent = que.front();
        que.pop_front();

        if(pCurrent != last)
            cout<<pCurrent->m_nValue<<" ";
        else
            cout<<pCurrent->m_nValue<<endl;

        if(pCurrent->m_pleft != NULL)
        {
            nlast = pCurrent->m_pleft;
            que.push_back(pCurrent->m_pleft);
        }

        if(pCurrent->m_pright != NULL)
        {
            nlast = pCurrent->m_pright;
            que.push_back(pCurrent->m_pright);
        }

        if(pCurrent == last)
            last = nlast;
    }
}


void addBSTreeNode(BSTreeNode *&pCurrent, int value)
{
    if(pCurrent == NULL)
    {
        BSTreeNode *pBSTree = new BSTreeNode();
        pBSTree->m_nValue = value;
        pBSTree->m_pleft = NULL;
        pBSTree->m_pright = NULL;
        pCurrent = pBSTree;
    }
    else
    {
        if((pCurrent->m_nValue) > value)
            addBSTreeNode(pCurrent->m_pleft, value);
        else if((pCurrent->m_nValue) < value)
            addBSTreeNode(pCurrent->m_pright, value);   
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章