Created
October 31, 2020 14:21
-
-
Save TheWebDevel/57748b2b7df84469bd847bc7d6ed7b8a to your computer and use it in GitHub Desktop.
A Tree implementation in Node JS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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