Skip to content

Instantly share code, notes, and snippets.

@TheWebDevel
Created October 31, 2020 14:21
Show Gist options
  • Save TheWebDevel/57748b2b7df84469bd847bc7d6ed7b8a to your computer and use it in GitHub Desktop.
Save TheWebDevel/57748b2b7df84469bd847bc7d6ed7b8a to your computer and use it in GitHub Desktop.
A Tree implementation in Node JS.
class Node {
constructor(data, children = []) {
this.data = data;
this.children = children;
}
add(data) {
let node = new Node(data);
this.children.push(node);
}
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;
}
traverseBF(fn) {
let buffer = [];
if (this.root) {
buffer.push(this.root);
while (buffer.length) {
let firstNode = buffer.shift();
fn(firstNode);
buffer = [...buffer, ...firstNode.children];
}
}
}
traverseDF(fn) {
let buffer = [];
if (this.root) {
buffer.push(this.root);
while (buffer.length) {
let firstNode = buffer.shift();
fn(firstNode);
buffer = [...firstNode.children, ...buffer];
}
}
}
}
module.exports = { Tree, Node };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment