[英]Find the path to parent node in a tree from a given node
Given a tree
describe below, given an node
say 9
print the path from give node to root
node.给定下面描述的
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
}
]
}
for example if 9 is given output should be then output should be 1, 3, 9
例如,如果给定 9 output 应该是 output 应该是
1, 3, 9
as suggested, you can use a dfs algorithm.如建议的那样,您可以使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.