Given a tree
describe below, given an node
say 9
print the path from give node to root
node.
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
as suggested, you can use a dfs algorithm.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.