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] ]
/**
* 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) {
vector<vector<int>> ans;
if (root == NULL) return ans;
vector<int> level_Number;
queue<TreeNode*> T;
T.push(root);
int levelPostion=0;
int levelNow = 1;
int nextLevel=0;
while (!T.empty())
{
TreeNode * temp = T.front();
T.pop();
if (temp->left != NULL)
{
T.push(temp->left);
nextLevel++;
}
if (temp->right != NULL)
{
T.push(temp->right);
nextLevel++;
}
levelPostion++;
level_Number.push_back(temp->val);
if (levelPostion == levelNow)
{
ans.push_back(level_Number);
level_Number.clear();
levelPostion = 0;
levelNow = nextLevel;
nextLevel = 0;
}
}
return ans;
}
};