MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / Node

Class Node

graphs/depth-first-search.js:1–21  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Node {
2 constructor(name) {
3 this.name = name;
4 this.children = [];
5 }
6
7 addChild(name) {
8 this.children.push(new Node(name));
9 return this;
10 }
11
12 // time O(v + e) where v are the vertices and e the edges of the graph
13 // space O(v) because we are using recursion we could have v elements in the call stack
14 depthFirstSearch(array) {
15 array.push(this.name);
16 for (const child of this.children) {
17 child.depthFirstSearch(array);
18 }
19 return array;
20 }
21}
22
23const graph = new Node("A");
24graph.addChild("B").addChild("C").addChild("D");

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected