分層打印二叉樹


 題目:給定一棵二叉樹,要求按分層遍歷該二叉樹,即從上到下按層次訪問該二叉樹(每一層將單獨輸出一行),每一層要求訪問的順序從左到右。

答:

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

struct TreeNode 
{
    int m_nValue;
    TreeNode *m_pLeft;
    TreeNode *m_pRight;
};

//假定所創建的二叉樹如下圖所示
/*
                                             1
                                          /     \
                                         2       3
                                        / \      / 
                                       4   3    6
                                      / \   \  / \
                                     7   8  9  10 11
                                    /     \
                                   12      13
                                          /
                                         14
*/
void CreateBitree(TreeNode *&pNode, fstream &fin)
{
    int dat;
    fin>>dat;
    if(dat == 0)
    {
        pNode = NULL;
    }
    else 
    {
        pNode = new TreeNode();
        pNode->m_nValue = dat;
        pNode->m_pLeft = NULL;
        pNode->m_pRight = NULL;
        CreateBitree(pNode->m_pLeft, fin);      
        CreateBitree(pNode->m_pRight, fin); 
    }
}

void PrintTreeByLevel(TreeNode *pHead)
{
    if (NULL == pHead)
    {
        return;
    }
    vector<TreeNode*> vec;
    vec.push_back(pHead);int cur = 0;
    int last = 0;
    while(cur < vec.size())
    {
        last = vec.size();
        while (cur < last)
        {
            cout<<vec[cur]->m_nValue<<"  ";
            if (NULL != vec[cur]->m_pLeft)
            {
                vec.push_back(vec[cur]->m_pLeft);
            }
            if (NULL != vec[cur]->m_pRight)
            {
                vec.push_back(vec[cur]->m_pRight);
            }
            cur++;
        }
        cout<<endl;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    fstream fin("tree.txt");
    TreeNode *pHead = NULL;
    CreateBitree(pHead, fin);
    PrintTreeByLevel(pHead);
    return 0;
}

運行界面如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM