Title Description
Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each line of output layer.
Thinking
Using the idea of the queue
Code
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> res_p;
if(pRoot == NULL)
return res;
queue<TreeNode*> q_Tree;
q_Tree.push(pRoot);
res_p.push_back(pRoot->val);
res.push_back(res_p);
res_p.clear();
int count = 1;
while(q_Tree.size()>0)
{
int number = q_Tree.size();
while(number > 0)
{
TreeNode* current = q_Tree.front();
q_Tree.pop();
if(current->left)
{
q_Tree.push(current->left);
res_p.push_back(current->left->val);
}
if(current->right)
{
q_Tree.push(current->right);
res_p.push_back(current->right->val);
}
number--;
}
if(res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
count++;
}
return res;
}
};