js递归遍历树形,根据id,到他本身以及他所有的直系父辈的id,并且放入一个数组中

文章介绍了如何通过递归遍历树形数组结构,查找指定节点及其所有父节点的Id。提供了三种不同的JavaScript实现方法,当找到目标节点时,将沿途经过的节点Id存储到结果数组中,最后返回这个数组。若未找到目标节点,则返回null。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决思路

可以通过递归遍历树形数组结构来实现该需求。具体步骤如下:

1.定义一个空数组 result,用于存放结果。

2.遍历树形数组结构,找到与给定 Id 匹配的节点。

3.将该节点的 Id 加入 result 数组。

4.如果该节点存在父节点,则将其父节点的 Id 加入 result 数组,并递归处理该父节点,直到根节点。

5.最终返回 result 数组。

数据准备

const tree = [
  {
    id: 1,
    name: "Node 1",
    children: [
      {
        id: 2,
        name: "Node 1.1",
        children: [],
      },
      {
        id: 3,
        name: "Node 1.2",
        children: [
          {
            id: 4,
            name: "Node 1.2.1",
            children: [],
          },
          {
            id: 5,
            name: "Node 1.2.2",
            children: [],
          },
        ],
      },
    ],
  },
  {
    id: 6,
    name: "Node 2",
    children: [],
  },
];

代码实现

方式一

function findAncestorsById(tree, id, result = []) {
  for (const node of tree) {
    if (node.id === id) {
      result.push(id);
      return result;
    }
    if (node.children.length) {
      const temp = findAncestorsById(node.children, id, result);
      if (temp) {
        result.push(node.id);
        return result;
      }
    }
  }
  return null;
}

 方式二

function findRegionById(tree, id, parents = []) {
  for (let i = 0; i < tree.length; i++) {
    const region = tree[i];
    if (region.id === id) {
      parents.push(region.id);
      return parents.reverse();
    } else if (region.children) {
      const found = findRegionById(region.children, id, parents);
      if (found) {
        parents.push(region.id);
        return found;
      }
    }
  }
  return null;
}

 方式三

function findNodeAndParentsById(tree, id, parents = []) {
  for (const node of tree) {
    if (node.id === id) {
      return [...parents, node.id];
    }

    if (node.children) {
      const result = findNodeAndParentsById(node.children, id, [
        ...parents,
        node.id,
      ]);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

获取结果

const id = 5;
const result = findNodeAndParentsById(tree, id);
console.log(result, "result++++++++++++++++++");

其中 tree 是树形数组结构,id 是给定的节点 Id,result 是用于存放结果的数组。

函数使用了递归的方式来遍历树形数组结构,并将匹配的节点的 Id 和其父节点的 Id 存入 result 数组中。

最终返回 result 数组。

如果遍历完整个 JSON 数据结构,仍然没有找到指定的节点,函数将返回 null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值