You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何从递归分类树中获取指定节点的所有父级ID数组

递归分类树父级ID查询实现

需求背景

现有支持无限层级嵌套的分类树结构,每个分类节点包含id字段和subCategories子分类数组,子分类结构和父级完全一致,结构示例如下:

let categoryTree = [
  {
    id: 1,
    subCategories: [
      {
        id: 2,
        subCategories: [
          {
            id: 3,
            subCategories: [],
          },
        ],
      },
      {
        id: 4,
        subCategories: [
          {
            id: 5,
            subCategories: [],
          },
        ],
      },
    ],
  },
  {
    id: 6,
    subCategories: [
      {
        id: 7,
        subCategories: [
          {
            id: 8,
            subCategories: [],
          },
        ],
      },
      {
        id: 9,
        subCategories: [
          {
            id: 10,
            subCategories: [],
          },
        ],
      },
    ],
  },
];

需要实现getParentIds函数,输入目标节点ID,返回该节点从根节点开始的所有递归父级ID数组,预期执行结果:

getParentIds(3) // 返回 [1,2]
getParentIds(8) // 返回 [6,7]
getParentIds(4) // 返回 [1]
getParentIds(1) // 返回 []

原代码缺陷

原有实现存在两个核心问题,无法适配全场景查询:

  • 递归遍历逻辑错误:recursiveFindParent的循环中,只要第一个节点的直接子节点没匹配到目标ID,就会直接递归进入该节点的子分支查找,完全跳过数组中后续的同级节点,比如查找id=8时,遍历完id=1的分支没找到就直接返回,根本不会访问id=6所在的分支。
  • 作用域传参错误:getParentIds调用recursiveFindParent时传入的categories没有定义来源,既没有作为函数参数传入,也没有正确引用全局的categoryTree变量。

最简可运行实现

单次深度优先遍历即可完成查询,不需要拆分多函数反复回溯,代码逻辑更简洁,遍历效率更高:

function getParentIds(targetId, categories = categoryTree, parentPath = []) {
  for (const node of categories) {
    // 匹配到目标节点,直接返回当前累计的父级路径
    if (node.id === targetId) return [...parentPath];
    // 存在子分类时,将当前节点ID加入路径,递归查找子分类
    if (node.subCategories?.length) {
      const matchResult = getParentIds(targetId, node.subCategories, [...parentPath, node.id]);
      // 子分支找到结果直接向上返回,不做多余遍历
      if (matchResult) return matchResult;
    }
  }
  // 当前分支无匹配返回null,继续遍历其他同级分支
  return null;
}

// 测试验证
console.log(getParentIds(3)); // [1,2]
console.log(getParentIds(8)); // [6,7]
console.log(getParentIds(4)); // [1]
console.log(getParentIds(1)); // []

内容的提问来源于stack exchange,提问作者xTheWolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:54:25