• 分层打印二叉树


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

    答:

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

    运行界面如下:

  • 相关阅读:
    careercup-树与图 4.6
    careercup-树与图 4.5
    careercup-树与图 4.4
    careercup-树与图 4.3
    oracle 建表时显示ORA-00904无效的标识符
    Unable to read TLD "META-INF/c.tld" from JAR file
    MIME TYPE
    JavaWeb response对象常用操作
    移动硬盘文件删除后,空间没有变大
    Redis 数据结构解析和命令指南
  • 原文地址:https://www.cnblogs.com/venow/p/2667705.html
Copyright © 2020-2023  润新知