Description
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
Answer
Using queue to store current layer of binary tree. Traverse each layer, pop out each node in the current layer and push next layer of tree nodes in the queue.
Code
C++
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root == NULL) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
vector<int> t;
int n = q.size();
for(int i = 0; i < n; ++i)
{
TreeNode *dummy = q.front();
q.pop();
t.push_back(dummy->val);
if(dummy->left != NULL)
q.push(dummy->left);
if(dummy->right != NULL)
q.push(dummy->right);
}
res.push_back(t);
}
return res;
}
};