Skip to content

Instantly share code, notes, and snippets.

@jordanrios94
Last active February 3, 2023 13:28
Show Gist options
  • Save jordanrios94/ac694c6f20178ffa9dea0f8b09fe5273 to your computer and use it in GitHub Desktop.
Save jordanrios94/ac694c6f20178ffa9dea0f8b09fe5273 to your computer and use it in GitHub Desktop.
Tree
/*
1) Create a node class.
- The constructor should accept an argument that gets assigned to the data property and initialise an empty arroy for storing children.
- The node class should have methods 'add' and 'remove'.
2) Create a tree class. The tree constructor should initialise a 'root' property to null.
3) Implement 'taverseBFS' and 'traverseDFS' on the tree 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;
});
}
}
class Tree {
constructor() {
this.root = null;
}
traverseBFJordanCorrectAttempt(fn) {
const nodes = [];
if (this.root) {
nodes.push(this.root);
while (nodes.length > 0) {
const currentNode = nodes[0];
fn(currentNode);
for (let node of currentNode.children) {
nodes.push(node);
}
nodes.shift();
}
}
}
traverseBF(fn) {
const arr = [this.root];
while (arr.length) {
const node = arr.shift();
arr.push(...node.children);
fn(node);
}
}
traverseDF(fn) {
const arr = [this.root];
while (arr.length) {
const node = arr.shift();
arr.unshift(...node.children);
fn(node);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment