What does this iterative DFS print?

from Trees and graphs
Node 24 intermediate 2 min

What does this iterative DFS print?

JavaScript
const graph = new Map([
  ["A", ["B", "C"]],
  ["B", ["D"]],
  ["C", ["D"]],
  ["D", []],
]);
const seen = new Set();
const order = [];
const stack = ["A"];

while (stack.length > 0) {
  const vertex = stack.pop();
  if (seen.has(vertex)) continue;
  seen.add(vertex);
  order.push(vertex);
  const neighbors = graph.get(vertex) ?? [];
  for (let index = neighbors.length - 1; index >= 0; index -= 1) {
    stack.push(neighbors[index]);
  }
}

console.log(order.join(" -> "));
Open in playground
Report an error