zoukankan      html  css  js  c++  java
  • 分层打印二叉树

     题目:给定一棵二叉树,要求按分层遍历该二叉树,即从上到下按层次访问该二叉树(每一层将单独输出一行),每一层要求访问的顺序从左到右。

    答:

    #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;
    }

    运行界面如下:

  • 相关阅读:
    python 生成器和推导式
    python 函数名 ,闭包 ,迭代器
    python 函数
    python BMI指数
    python 实现购物车的优化
    python 文件操作
    python set集合 深浅拷贝(难点)
    css中的float和position
    css一些简单的例子
    SQL测试题
  • 原文地址:https://www.cnblogs.com/venow/p/2667705.html
Copyright © 2011-2022 走看看