Skip to content

Instantly share code, notes, and snippets.

@samcorcos
Created August 29, 2018 04:29
Show Gist options
  • Save samcorcos/66d26563f021df117b1b3db1d42e8f36 to your computer and use it in GitHub Desktop.
Save samcorcos/66d26563f021df117b1b3db1d42e8f36 to your computer and use it in GitHub Desktop.
Depth-first Search Javascript
const tree = {
id: "1",
children: [
{id: "2", children: [
{id: "4", children: [
{id: "7", children: []}
]},
{id: "6", children: []},
]},
{id: "3", children: [
{id: "5", children: []},
]},
]
}
// takes in a tree and truncates to a max depth
const dfs = (node, id) => {
if (node.id === id) return true
for (let i = 0; i < node.children.length; i++) {
let found = dfs(node.children[i], id)
if (found) return true
}
return false
}
console.log(dfs(tree, "7")) // => true
console.log(dfs(tree, "5")) // => true
console.log(dfs(tree, "100")) // => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment