解题思路
用一个队列进行二叉树的层次遍历,先将根放入队列中,之后队列非空时,将当前层的pop出来,若有左右子树则入队。直到队列为空,遍历结束。
代码
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>>res;
if(root == NULL)
return res;
queue<TreeNode *>q;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int>cur;
while(size--){
TreeNode *tmp = q.front();
q.pop();
cur.push_back(tmp->val);
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
}
res.push_back(cur);
}
return res;
}
};