广度优先搜索
- 思路:
- 广度优先搜索对应的数据结构是队列,处理每一层时把下一层节点 push 到队列中;
- 使用 vector<vector> 数据结构存放结果;
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {std::vector<std::vector<int>> result;if (root == nullptr) {return result;}std::queue<TreeNode*> q;q.push(root);while (!q.empty()) {int levelSize = q.size();result.push_back(std::vector<int>());for (int idx = 0; idx < levelSize; ++idx) {auto node = q.front();q.pop();result.back().push_back(node->val);if (node->left) {q.push(node->left);}if (node->right) {q.push(node->right);}}}return result;}
};