题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
二叉树的层次遍历
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> > res;
if(!pRoot)
return res;
queue<TreeNode* > Q;
Q.push(pRoot);
while(!Q.empty())
{
vector<int> temp;
int len = Q.size();
for(int i = 0; i < len; i++)
{
TreeNode* node = Q.front();
Q.pop();
temp.push_back(node ->val);
if(node ->left)
Q.push(node ->left);
if(node ->right)
Q.push(node ->right);
}
res.push_back(temp);
}
return res;
}
};