【剑指offer】把二叉树打印成多行,C++实现

原创文章,转载请注明出处!

本题牛客网地址

博客文章索引地址

博客文章中代码的github地址

1.题目

      从上到下按层打印二叉树,同一层结点从左至右输出,每一层输出一行。例如:下面二叉树的打印结果为:

8

6 10

5 7 9 11

image


2.思路

      本题目使用队列和两个变量作为辅助,利用队列的先进先出策略,按层遍历二叉树。队列保存将要打印的节点,一个变量表示当前层中还没有打印的节点数,一个节点表示下一层节点的数目。

3.代码

  1 /*
  2 struct TreeNode {
  3     int val;
  4     struct TreeNode *left;
  5     struct TreeNode *right;
  6     TreeNode(int x) :
  7             val(x), left(NULL), right(NULL) {
  8     }
  9 };
 10 */
 11 class Solution {
 12 public:
 13         vector<vector<int> > Print(TreeNode* pRoot) {
 14 
 15             // 存储结果
 16             vector<vector<int>>  result; // 存储全部节点
 17             vector<int> temp;            // 存储某一层节点
 18 
 19             // 边界条件
 20             if(pRoot == nullptr)
 21                 return result;
 22 
 23             // 辅助容器:队列
 24             queue<TreeNode*> q;
 25             TreeNode* fr;
 26             int now_level=1;
 27             int next_level=0;
 28 
 29             // 根节点入队列
 30             q.push(pRoot);
 31 
 32             // 遍历队列
 33             while(!q.empty())
 34             {
 35                 // 节点弹出队列
 36                 fr=q.front();
 37                 temp.push_back(fr->val);
 38                 q.pop();
 39 
 40                 // 遍历节点左右子树
 41                 if(fr->left != NULL){
 42                     q.push(fr->left);
 43                     ++next_level;
 44                 }
 45                 if(fr->right != NULL){
 46                     q.push(fr->right);
 47                     ++next_level;
 48                 }
 49                 --now_level;
 50 
 51                 // 判断当前层是否打印完
 52                 if(now_level==0){
 53                     now_level=next_level;
 54                     next_level=0;
 55                     result.push_back(temp);
 56                     temp.clear(); // 清除一维vector
 57                 }
 58             }
 59 
 60            return result;
 61         }
 62 };



posted @ 2018-03-24 14:42  wanglei5205  阅读(1103)  评论(0编辑  收藏  举报
levels of contents