剑指offer第60题:把二叉树打印成多行

剑指offer第60题:把二叉树打印成多行

题目描述

把二叉树打印成多行

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

源码

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public: vector<vector<TreeNode*> > PrintTree(TreeNode* pRoot)
    {
        vector<vector<TreeNode*> > res;
        if(pRoot== NULL) return res;
        vector<TreeNode*> firstfloor;
        firstfloor.push_back(pRoot);
        res.push_back(firstfloor);
        int floor_num = 0;
        while(floor_num < res.size())
        {
            vector<TreeNode*> nextfloor;
            for(auto ptree: res[floor_num])
            {
                if(ptree->left  != NULL) nextfloor.push_back(ptree->left);
                if(ptree->right != NULL) nextfloor.push_back(ptree->right);
            }
            if(!nextfloor.empty())
            res.push_back(nextfloor);
            floor_num++;
        }
        return res;
    }
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot == NULL) return res;
        vector<vector<TreeNode*> > ptreenode;
        ptreenode = PrintTree(pRoot);
        for(int i = 0 ;i < ptreenode.size();i++)
        {
           vector<int> int_floor;
          for(int j = 0;j < ptreenode[i].size();j++)
          {
             int_floor.push_back(ptreenode[i][j]->val);
          }
         //if(i%2==1) reverse(int_floor.begin(),int_floor.end());
         res.push_back(int_floor);
        }
        return res;
    }
    
};
上一篇:又是被老板找的一天!js小数点后两位相加不等于小数点后两位,而是很多位!解决方法


下一篇:剑指offer第59题:按之字形顺序打印二叉树