题目链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
解题步骤:
- 题目要求层序遍历二叉树,自然想到使用广度优先搜索BFS进行解题
- 我们可以借助队列queue来实现广度优先搜索
- 基本思路是:
- 先把根接节点放入队列
- 取出根节点,并依次将根节点的非空左节点和非空右节点放入队列
- 对每一层的所有节点都执行与根节点一样的操作,并将节点值放入同个列表中
- 直到队列为空,返回所有列表
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>> res;
if (root == NULL)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int cursize = q.size();
res.push_back(vector<int> {});
for (int i = 0; i < cursize; i++) {
TreeNode* front = q.front();
q.pop();
res.back().push_back(front->val);
if (front->left)
q.push(front->left);
if (front->right)
q.push(front->right);
}
}
return res;
}
};