题目链接:102. 二叉树的层序遍历 - 力扣(LeetCode)
借助队列实现广度优先搜索,遍历节点把子树入队
class Solution {
public:vector<vector<int>> levelOrder(TreeNode *root) {if (root == nullptr)return {};vector<vector<int>> ans;queue<TreeNode *> level;level.push(root);while (!level.empty()) {int levelSize = level.size();vector<int> temp;while (levelSize--) {TreeNode *node = level.front();level.pop();temp.push_back(node->val);if (node->left)level.push(node->left);if (node->right)level.push(node->right);}ans.push_back(std::move(temp));}return ans;}
};