题目描述:
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[[8], [12, 2], [6], [4]]
分析:
方法一:
每层入队完成后对队列里加入一个标志空节点,注意只有队列非空时才加入。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int> > v;
if(!root) return v;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> ve;
while(!q.empty()){
TreeNode* u = q.front();
q.pop();
if(u){
ve.push_back(u->val);
if(u->left) q.push(u->left);
if(u->right) q.push(u->right);
}
else{
if(!q.empty()) q.push(NULL);
v.push_back(ve);
ve.clear();
}
}
return v;
}
};
方法二:
记录下每层结点的个数。
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int> > v;
if(!root) return v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> ve;
int n = q.size();
while(n-- && !q.empty()){
TreeNode* u = q.front();
q.pop();
ve.push_back(u->val);
if(u->left) q.push(u->left);
if(u->right) q.push(u->right);
}
v.push_back(ve);
}
return v;
}
};