(个人水平有限,请见谅!)
题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
代码示例:
/*
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 size = q.size();
for (int i = 0; i < size; i++)
{
temp.push_back(q.front()->val);
if (q.front()->left != NULL)
q.push(q.front()->left);
if (q.front()->right != NULL)
q.push(q.front()->right);
q.pop();
}
res.push_back(temp);
}
return res;
}
};