剑指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;
}
};