102.二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
来源:力扣(LeetCode)
链接:link
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析:本题使用宽度优先搜索(BFS),对每一层的元素同时进入队列,然后出队时同时出队,再换下一层的同时入队。
C++源码:
/**
* 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;
queue<TreeNode*> q;
TreeNode* p = root;
q.push(root);
while(!q.empty())
{
vector<int> step;
int width = q.size();
for(int i = 0;i < width;i++)//这一层循环用来将之前层的元素出队,将下一层元素入队
{
p = q.front();
step.push_back(p->val);
q.pop();
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
ans.push_back(step);
}
return ans;
}
};