Node
class.
data
property and initialize an empty array for storing children
.Node
class should have methods add
and remove
.Tree
class.
root
property to null
.traverseBF
(breadth first) and traverseDepthFirst
(depth first) on the Tree
class.
Node
class
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
add(data) {
this.children.push(new Node(data));
}
remove(data) {
this.children = this.children.filter((node) => {
return node.data !== data;
})
}
}
Tree
class
class Tree {
constructor() {
this.root = null;
}
/**
* @method traverseBF
* @description Executes a breadth-first traversal of the tree.
*/
traverseBF(fn) {
const arr = [this.root];
while (arr.length > 0) {
const node = arr.shift();
arr.push(...node.children);
fn(node);
}
}
/**
* @method traverseDF
* @description Executes a depth-first traversal of the tree.
*/
traverseDF(fn) {
const arr = [this.root];
while (arr.length > 0) {
const node = arr.shift();
arr.unshift(...node.children);
fn(node);
}
}
}