export interface TreeNode { id: string title: string children?: TreeNode[] } // 递归查找节点的方法 export function findNodeById(tree: TreeNode[], id: string): TreeNode | null { // debugger for (const node of tree) { if (node.id === id) { return node // 找到匹配的节点 } if (node.children) { const result = findNodeById(node.children, id) // 递归查找子节点 if (result) { return result // 如果在子节点中找到,返回结果 } } } return null // 未找到匹配的节点 } // 递归查找面包屑路径的方法 export function findBreadcrumbPath( tree: TreeNode[], targetId: string, path: TreeNode[] = [], ): TreeNode[] | null { for (const node of tree) { // 将当前节点加入路径 const currentPath = [...path, node] // 如果当前节点是目标节点,返回当前路径 if (node.id === targetId) { return currentPath } // 如果当前节点有子节点,递归查找 if (node.children) { const result = findBreadcrumbPath(node.children, targetId, currentPath) if (result) { return result // 如果在子节点中找到目标节点,返回路径 } } } // 未找到目标节点 return null } // 生成面包屑导航数组的方法 export function generateBreadcrumbArray(tree: TreeNode[], targetId: string): TreeNode[] | null { const path = findBreadcrumbPath(tree, targetId) if (path) { // 返回包含节点信息的面包屑导航数组 return path } return null // 未找到目标节点 }