题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
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>> tVecVec;
if(pRoot == NULL)
{
return tVecVec;
}
queue<TreeNode*> que;
que.push(pRoot);
while(que.size())
{
int length = que.size();
vector<int> vec;
for(int i = 0; i < length; ++i)
{
TreeNode* tmp = que.front();
vec.push_back(tmp->val);
que.pop();
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
}
tVecVec.push_back(vec);
vec.clear();
}
return tVecVec;
}
};
网友评论