考虑到下面的tree
,假设有node
说9
打印从给定节点到root
节点的路径。
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
答案 0 :(得分:2)
根据建议,您可以使用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);