2023-01-06 03:39:19 +08:00
|
|
|
/**
|
2022-11-25 02:04:38 +08:00
|
|
|
* File: binary_tree_bfs.cpp
|
|
|
|
* Created Time: 2022-11-25
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
*/
|
|
|
|
|
2023-04-24 04:11:18 +08:00
|
|
|
#include "../utils/common.hpp"
|
2022-11-27 04:19:16 +08:00
|
|
|
|
2022-11-29 02:21:49 +08:00
|
|
|
/* 层序遍历 */
|
2023-04-14 03:44:02 +08:00
|
|
|
vector<int> levelOrder(TreeNode *root) {
|
2023-04-09 04:32:17 +08:00
|
|
|
// 初始化队列,加入根节点
|
2023-04-14 03:44:02 +08:00
|
|
|
queue<TreeNode *> queue;
|
2022-11-29 02:21:49 +08:00
|
|
|
queue.push(root);
|
|
|
|
// 初始化一个列表,用于保存遍历序列
|
|
|
|
vector<int> vec;
|
|
|
|
while (!queue.empty()) {
|
2023-04-14 03:44:02 +08:00
|
|
|
TreeNode *node = queue.front();
|
|
|
|
queue.pop(); // 队列出队
|
|
|
|
vec.push_back(node->val); // 保存节点值
|
2022-11-29 03:21:02 +08:00
|
|
|
if (node->left != nullptr)
|
2023-04-14 03:44:02 +08:00
|
|
|
queue.push(node->left); // 左子节点入队
|
2022-11-29 03:21:02 +08:00
|
|
|
if (node->right != nullptr)
|
2023-04-09 04:32:17 +08:00
|
|
|
queue.push(node->right); // 右子节点入队
|
2022-11-29 02:21:49 +08:00
|
|
|
}
|
|
|
|
return vec;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
int main() {
|
|
|
|
/* 初始化二叉树 */
|
|
|
|
// 这里借助了一个从数组直接生成二叉树的函数
|
2023-04-14 03:44:02 +08:00
|
|
|
TreeNode *root = vecToTree(vector<int>{1, 2, 3, 4, 5, 6, 7});
|
2022-11-29 02:21:49 +08:00
|
|
|
cout << endl << "初始化二叉树\n" << endl;
|
2023-04-14 03:44:02 +08:00
|
|
|
printTree(root);
|
2022-11-29 02:21:49 +08:00
|
|
|
|
|
|
|
/* 层序遍历 */
|
2023-02-15 03:36:22 +08:00
|
|
|
vector<int> vec = levelOrder(root);
|
2023-04-09 04:32:17 +08:00
|
|
|
cout << endl << "层序遍历的节点打印序列 = ";
|
2023-04-14 03:44:02 +08:00
|
|
|
printVector(vec);
|
2022-11-29 02:21:49 +08:00
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|