Dev HelpersOpen library
← Back

Traverse a tree depth-first

Traverse a tree depth-first. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const tree = {
  value: "a",
  children: [
    { value: "b", children: [] },
    { value: "c", children: [] },
  ],
};
const visit = (node) => [node.value, ...node.children.flatMap(visit)];
console.log(visit(tree));

Sample output

[ 'a', 'b', 'c' ]