题目:给定一棵二叉树,要求按分层遍历该二叉树,即从上到下按层次访问该二叉树(每一层将单独输出一行),每一层要求访问的顺序从左到右。
答:
#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; }
运行界面如下: