tree.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. export interface TreeNode {
  2. id: string
  3. title: string
  4. children?: TreeNode[]
  5. }
  6. // 递归查找节点的方法
  7. export function findNodeById(tree: TreeNode[], id: string): TreeNode | null {
  8. // debugger
  9. for (const node of tree) {
  10. if (node.id === id) {
  11. return node // 找到匹配的节点
  12. }
  13. if (node.children) {
  14. const result = findNodeById(node.children, id) // 递归查找子节点
  15. if (result) {
  16. return result // 如果在子节点中找到,返回结果
  17. }
  18. }
  19. }
  20. return null // 未找到匹配的节点
  21. }
  22. // 递归查找面包屑路径的方法
  23. export function findBreadcrumbPath(
  24. tree: TreeNode[],
  25. targetId: string,
  26. path: TreeNode[] = [],
  27. ): TreeNode[] | null {
  28. for (const node of tree) {
  29. // 将当前节点加入路径
  30. const currentPath = [...path, node]
  31. // 如果当前节点是目标节点,返回当前路径
  32. if (node.id === targetId) {
  33. return currentPath
  34. }
  35. // 如果当前节点有子节点,递归查找
  36. if (node.children) {
  37. const result = findBreadcrumbPath(node.children, targetId, currentPath)
  38. if (result) {
  39. return result // 如果在子节点中找到目标节点,返回路径
  40. }
  41. }
  42. }
  43. // 未找到目标节点
  44. return null
  45. }
  46. // 生成面包屑导航数组的方法
  47. export function generateBreadcrumbArray(tree: TreeNode[], targetId: string): TreeNode[] | null {
  48. const path = findBreadcrumbPath(tree, targetId)
  49. if (path) {
  50. // 返回包含节点信息的面包屑导航数组
  51. return path
  52. }
  53. return null // 未找到目标节点
  54. }