# LeetCode题目：Binary Tree Level Order Traversal

By | 2012 年 12 月 7 日

Binary Tree Level Order Traversal
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 binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector > levelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector > ret;
if(NULL == root) return ret;
queue trace;
trace.push(root);
trace.push(NULL);
vector levelVals;
while(true) {
TreeNode *cur = trace.front();
trace.pop();
if(NULL == cur) {
ret.push_back(levelVals);
levelVals.erase(levelVals.begin(),levelVals.end());
if(trace.size())
trace.push(NULL);
else
break;
} else {
levelVals.push_back(cur->val);
if(cur->left) trace.push(cur->left);
if(cur->right) trace.push(cur->right);
}
}
return ret;
}
};
```

Code rewrite at 2012-12-22, 24ms pass the large test set

```class Solution {
public:
vector > levelOrder(TreeNode *root) {
vector > ret;

queue q;
if(root) {
q.push(root);
q.push(NULL);
}

vector level;
while(q.size()) {
TreeNode *cur = q.front();
q.pop();
if(cur) {
level.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
} else {
ret.push_back(level);
level.erase(level.begin(),level.end());
if(q.size()) q.push(NULL);
}
}

return ret;
}
};
```