# 102. 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,null,null,15,7],

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

[
[3],
[9,20],
[15,7]
]


/**二叉树的bfs和队列个数，可分层处理到每一层的的节点。
* 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> > outer;
vector<int> inner;
queue<TreeNode*> q;
if (root)
q.push(root);
else
return outer;
while (!q.empty())
{
int size=q.size();//当前队列的个数，用来将当前层的节点全从队列中移除。
inner.clear();
while (size-->0)
{
TreeNode* t=q.front();
q.pop();
inner.push_back(t->val);
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
outer.push_back(inner);
}
return outer;
}

};

• 本文已收录于以下专栏：

举报原因： 您举报文章：102. Binary Tree Level Order Traversal 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)