# leetcode No102. Binary Tree Level Order Traversal

Datetime:2016-08-23 01:17:06         Topic: LeetCode          Share        Original >>

## Question:

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]
]```

## Accepted Code：

```/**
* 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>> res;
if(root==NULL)return res;
queue<TreeNode*> q;
vector<int> temp;
q.push(root);
int curCount=1;
int nextCount=0;
while(!q.empty())
{
TreeNode* curNode=q.front();
temp.push_back(curNode->val);
q.pop();
curCount--;
if(curNode->left)
{
q.push(curNode->left);
nextCount++;
}
if(curNode->right)
{
q.push(curNode->right);
nextCount++;
}
if(curCount==0)
{
curCount=nextCount;
nextCount=0;
res.push_back(temp);
temp.clear();
}
}
return res;
}
};```