# 题目链接

Binary Tree Level Order Traversal – LeetCode

• 不要访问空结点

# 解法

``````/**
* 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:
typedef vector<vector<int>> v;
typedef TreeNode* node;
void bfs(int level,node n,v& ret)
{
if(ret.size() == level) ret.push_back({});
ret[level].push_back(n->val);
if(n->left) bfs(level+1,n->left,ret);
if(n->right) bfs(level+1,n->right,ret);
}
vector<vector<int>> levelOrder(TreeNode* root) {
v ret;
if(!root) return ret;
queue<node> q;
q.push(root);
bfs(0,root,ret);
return ret;
}
};``````

``````/**
* 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:
typedef vector<vector<int>> v;
typedef TreeNode* node;
vector<vector<int>> levelOrder(TreeNode* root) {
v ret;
if(!root) return ret;
queue<node> q;
q.push(root);
while(!q.empty())
{
vector<int> aLevel;
for(int i = q.size();i > 0;--i)
{
node n = q.front();
q.pop();
aLevel.push_back(n->val);
if(n->left) q.push(n->left);
if(n->right) q.push(n->right);
}
ret.push_back(aLevel);
}
return ret;
}
};``````

# 小结

原文作者：闽A2436
原文地址: https://www.cnblogs.com/multhree/p/10542388.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。