题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ans;
vector<int> flag;
if(!pRoot)
return ans;
queue<TreeNode*> temp;
queue<TreeNode*> tempPlus;
temp.push(pRoot);
while(!temp.empty())
{
TreeNode* cur = temp.front();
flag.push_back(cur->val);
temp.pop();
if(cur->left)
tempPlus.push(cur->left);
if(cur->right)
tempPlus.push(cur->right);
if(temp.empty())
{
temp = tempPlus;
queue<TreeNode*> odd;
tempPlus = odd;
ans.push_back(flag);
flag.clear();
}
}
return ans;
}
};