Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as:
C++
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
vector<int> level;
q.push(nullptr);
while(!q.empty())
{
TreeNode* temp = q.front();
q.pop();
if(temp != nullptr)
{
level.push_back(temp->val);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
else
{
if(!level.empty())
{
res.push_back(level);
level.clear();
q.push(nullptr);
}
}
}
return res;
}