zoukankan      html  css  js  c++  java
  • 【剑指offer】把二叉树打印成多行

    题目链接:把二叉树打印成多行

     

    题意:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

     

    题解:用一个队列,每层压入队列,再放入数组里。层序遍历。

     

    代码:

     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             vector<vector<int>> ans;
    15             vector<int> level;
    16             if(pRoot == NULL)    return ans;
    17             
    18             queue<TreeNode*> q;
    19             q.push(pRoot);
    20             int cnt = 0;
    21             while(!q.empty()){
    22                 level.clear();
    23                 cnt = q.size();
    24                 while(cnt--){
    25                     TreeNode* node = q.front();
    26                     level.push_back(node->val);
    27                     if(node->left)    q.push(node->left);
    28                     if(node->right)    q.push(node->right);
    29                     q.pop();
    30                 }
    31                 ans.push_back(level);
    32             }
    33             return ans;
    34         }
    35     
    36 };
  • 相关阅读:
    类的组合
    类的继承和派生
    面向对象编程
    正则表达式
    sys模块 logging模块 序列化模块
    time 模块,random模块,os模块
    递归函数
    interface有没有继承Object
    UTF-8和GBK的区别
    九皇后
  • 原文地址:https://www.cnblogs.com/Asumi/p/12423794.html
Copyright © 2011-2022 走看看