javascript - 从给定节点查找树中父节点的路径

标签 javascript algorithm data-structures tree

给定下面描述的,给定节点9 打印从给定节点到的路径节点。

let sampleData = {
id: 1,
children: [{
    id: 2,
    children: [{
        id: 5,
        children: [{
            id: 8
        }]
    },
        {
            id: 6
        }
    ]
},
    {
        id: 3,
        children: [{
            id: 9
        }, {id: 10 }]}, {
        id: 4
     }
     ]
  }

例如,如果给定 9,则输出应为 1 , 3, 9

最佳答案

按照建议,您可以使用 dfs 算法。

function dfs(o, target){
    if(o.id == target) return [target];
    if(!o.children) return false;
    let path;
    o.children.find(x=>path=dfs(x, target));
    if(path){
        return [o.id].concat(path);
    }
};
let sampleData={"id":1,"children":[{"id":2,"children":[{"id":5,"children":[{"id":8}]},{"id":6}]},{"id":3,"children":[{"id":9},{"id":10}]},{"id":4}]}
let path;
[sampleData].find(x=>path=dfs(x, 9))
console.log(path);

关于javascript - 从给定节点查找树中父节点的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761627/

相关文章:

javascript - ng-click 不适用于 ng-if

javascript - 如何将包含多个 js 语句的字符串拆分为一个字符串数组,每个字符串包含一个语句?

javascript - 将 QUnit 与 JSTestDriver 结合使用

algorithm - AS3 创建 6 ^ 20 结果的算法

java - 为空格分隔的单词实现分类器算法的问题

javascript - 裁剪比例公式

c++ - union 工作不正常

仅限 Javascript : Function renders a dropdown and table where the value from the dropdown is needed to filter the table

java - 从分布不均匀的集合中选择随机元素?

perl - Perl 散列名称(在声明时)可以在同一个散列中使用吗?