题目描述
题目链接:二叉树的层序遍历
根据上一篇文章的模板可以直接写代码,需要改变的就是将N叉树的child改为二叉树的left和right。
代码
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if (root == nullptr)
return res;
q.push(root);
while(q.size())
{
vector<int> tmp;
int sz = q.size();
for (int i = 0; i < sz; ++ i)
{
TreeNode* t = q.front();
q.pop();
tmp.push_back(t->val);
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
res.push_back(tmp);
}
return res;
}
};