问题描述:
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]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
AC代码如下:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int> >res;//结果数组
if(root == NULL)
return res;
queue<TreeNode*>Queue;
Queue.push(root);
while(Queue.size() > 0)
{
vector<int>row;//每一行
queue<TreeNode*>temp;
while(Queue.size() > 0)
{
TreeNode * node = Queue.front();
Queue.pop();
if(node->left != NULL)
temp.push(node->left);
if(node->right != NULL)
temp.push(node->right);
row.push_back(node->val);
}
Queue = temp;
res.push_back(row);
}
return res;
}