2022-12-04 12:26:09 +08:00
|
|
|
/**
|
2023-03-03 01:34:53 +08:00
|
|
|
* File: binary_tree_bfs.js
|
2022-12-04 12:26:09 +08:00
|
|
|
* Created Time: 2022-12-04
|
|
|
|
* Author: IsChristina (christinaxia77@foxmail.com)
|
|
|
|
*/
|
|
|
|
|
2023-04-17 21:58:11 +08:00
|
|
|
const { arrToTree } = require('../modules/TreeNode');
|
|
|
|
const { printTree } = require('../modules/PrintUtil');
|
2022-12-04 12:26:09 +08:00
|
|
|
|
|
|
|
/* 层序遍历 */
|
2023-02-15 03:36:22 +08:00
|
|
|
function levelOrder(root) {
|
2023-04-09 04:32:17 +08:00
|
|
|
// 初始化队列,加入根节点
|
2023-03-03 01:34:53 +08:00
|
|
|
const queue = [root];
|
2022-12-04 12:26:09 +08:00
|
|
|
// 初始化一个列表,用于保存遍历序列
|
2023-03-03 01:34:53 +08:00
|
|
|
const list = [];
|
2022-12-04 12:26:09 +08:00
|
|
|
while (queue.length) {
|
2023-04-17 21:58:11 +08:00
|
|
|
let node = queue.shift(); // 队列出队
|
|
|
|
list.push(node.val); // 保存节点值
|
|
|
|
if (node.left) queue.push(node.left); // 左子节点入队
|
|
|
|
if (node.right) queue.push(node.right); // 右子节点入队
|
2022-12-04 12:26:09 +08:00
|
|
|
}
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
/* 初始化二叉树 */
|
|
|
|
// 这里借助了一个从数组直接生成二叉树的函数
|
2023-03-03 01:34:53 +08:00
|
|
|
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
|
2023-04-17 21:58:11 +08:00
|
|
|
console.log('\n初始化二叉树\n');
|
2022-12-04 23:14:09 +08:00
|
|
|
printTree(root);
|
2022-12-04 12:26:09 +08:00
|
|
|
|
|
|
|
/* 层序遍历 */
|
2023-03-03 01:34:53 +08:00
|
|
|
const list = levelOrder(root);
|
2023-04-17 21:58:11 +08:00
|
|
|
console.log('\n层序遍历的节点打印序列 = ' + list);
|