export type HierarchyStructure = T & { children?: HierarchyStructure[]; }; /** * 执行深度优先遍历 * * 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 */ export function dfs( node: N, visitor: (node: N, depth: number) => void, navigator: (node: N) => N[] | undefined, mode: 'BT' | 'TB', depth: number = 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 */ export function bfs(node: N, visitor: (node: N, depth: number) => void, navigator: (node: N) => N[] | undefined) { const queue: [N, number][] = [[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]); } } } }