"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dfs = dfs;
exports.bfs = bfs;
/**
* 执行深度优先遍历
*
* perform depth first traversal
* @param node - 起始节点 | start node
* @param visitor - 访问节点函数 | visitor function
* @param navigator - 获取子节点函数 | get children function
* @param mode - 访问模式,BT: 自底向上访问,TB: 自顶向下访问 | traverse mode, BT: bottom to top, TB: top to bottom
* @param depth - 当前深度 | current depth
*/
function dfs(node, visitor, navigator, mode, depth = 0) {
if (mode === 'TB')
visitor(node, depth);
const children = navigator(node);
if (children) {
for (const child of children) {
dfs(child, visitor, navigator, mode, depth + 1);
}
}
if (mode === 'BT')
visitor(node, depth);
}
/**
* 执行广度优先遍历
*
* perform breadth first traversal
* @param node - 起始节点 | start node
* @param visitor - 访问节点函数 | visitor function
* @param navigator - 获取子节点函数 | get children function
*/
function bfs(node, visitor, navigator) {
const queue = [[node, 0]];
while (queue.length) {
const [current, depth] = queue.shift();
visitor(current, depth);
const children = navigator(current);
if (children) {
for (const child of children) {
queue.push([child, depth + 1]);
}
}
}
}
//# sourceMappingURL=traverse.js.map