1,题目要求
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
2,题目思路
对于这道题,要求将一颗二叉树按照层次进行输出。
其实就是二叉树层次遍历的一个变种,区别在于,我们在遍历时,只需要对当前队列中的节点数提前做一个统计,就可以知道当前层有多少个节点了。
3,代码实现
/*
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) {
if(!pRoot)
return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty()){
int size = q.size();
vector<int> level;
for(int i = 0;i<size;i++){
TreeNode* curr = q.front();
level.push_back(curr->val);
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
q.pop();
}
res.push_back(level);
}
return res;
}
};