如何在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
相关产品推荐
相关产品推荐

