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

如何在nodes数组中生成仅指向更深depth节点的next数组?

解决图节点中生成过滤回溯节点的next数组问题

我来帮你搞定这个问题!你遇到的核心问题是没法正确获取子节点对应的depth值,而且原代码里的遍历和查找逻辑都存在一些小问题,导致没法生成正确的next数组。

先说说你原代码的几个问题

  • 用for...in遍历children数组是错误的,它会遍历数组的索引(字符串类型),而不是你需要的节点ID值;
  • 查找子节点depth的逻辑完全不对:nodes.id === child,nodes是数组,根本没有id属性,你需要通过子节点ID去数组里找到对应的节点对象;
  • childDepth的作用域没有控制好,很容易出现值混乱的情况。

正确的解决方案

最高效的方式是先创建一个节点ID到节点对象的映射表,这样可以快速通过ID找到对应的节点,不用每次遍历整个数组。然后我们只需要遍历每个节点,过滤掉children中depth小于等于当前节点的节点,剩下的就是next数组的内容。

完整代码示例

const nodes = [
 { "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
 { "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
 { "id": 256, "depth": 2, "children": [265], "next": [] },
 { "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
 { "id": 260, "depth": 2, "children": [210], "next": [] },
 { "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
 { "id": 269, "depth": 2, "children": [265], "next": [] },
 { "id": 271, "depth": 2, "children": [265], "next": [] },
 { "id": 388, "depth": 2, "children": [265], "next": [] },
 { "id": 391, "depth": 2, "children": [210], "next": [] },
 { "id": 394, "depth": 2, "children": [265], "next": [] },
 { "id": 395, "depth": 1, "children": [37], "next": [] },
 { "id": 396, "depth": 3, "children": [259, 413], "next": [] },
 { "id": 397, "depth": 3, "children": [259], "next": [] },
 { "id": 413, "depth": 4, "children": [396], "next": [] }
];

// 第一步:创建ID到节点的映射,O(1)快速查找
const nodeMap = new Map();
nodes.forEach(node => {
  nodeMap.set(node.id, node);
});

// 第二步:遍历每个节点,生成过滤后的next数组
nodes.forEach(node => {
  node.next = node.children.filter(childId => {
    const childNode = nodeMap.get(childId);
    // 确保找到子节点,且子节点depth大于当前节点depth
    return childNode && childNode.depth > node.depth;
  });
});

// 可以打印结果验证
console.log(nodes);

运行后的正确结果示例

几个关键节点的next数组会变成这样:

  • 节点37(depth 0):next: [210, 395, 265](所有子节点depth都大于0)
  • 节点210(depth 1):next: [260, 259, 391](剔除了depth 0的节点37)
  • 节点259(depth 2):next: [397, 396](剔除了depth 1的节点210)
  • 节点396(depth 3):next: [413](剔除了depth 2的节点259)
  • 节点260(depth 2):next: [](子节点210的depth小于2)

这样就完美解决了回溯节点的问题,你可以放心用这个代码来遍历图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:24:08