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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q1;
vector<vector<int>> result;
vector<int> temp;
if(!root)
return result;
q1.push(root);
do
{
queue<TreeNode*> q2;
temp.clear();
while(!q1.empty())
{
TreeNode* Node = q1.front();
q1.pop();
temp.push_back(Node->val);
if(Node->left)
q2.push(Node->left);
if(Node->right)
q2.push(Node->right);
}
q1 = q2;
result.push_back(temp);
}while(!q1.empty());
return result;
}
};