In the examples below we show how to implement Tree in Javascript including Breadth-First-Search and Depth-First-Search
class Node {
constructor(data)
this.data = data;
this.children = [];
}
addData(data) {
this.children.push(new Node(data));
}
removeData(data) {
this.children = this.childern.filter((item)=> {
return item.data !== data;
});
}
}
class Tree {
constructor(data) {
this.root = data;
}
breadth_first_search(fn) {
const arr = [this.root];
while(arr.length) {
const node = arr.shift();
arr.push(...node.children);
fn(node);
}
}
depth_first_search(fn) {
const arr = [this.root];
while(arr.length) {
const node = arr.shift();
arr.unshift(...node.children);
fn(node);
}
}
}
///test
const letters = [];
const t = new Tree();
t.root = new Node('a');
t.root.add('b');
t.root.add('c');
t.root.children[0].add('d');
let letters = [];
const t = new Tree();
t.root = new Node('a');
t.root.add('b');
t.root.add('d');
t.root.children[0].add('c');
t.breadth_first_search(node => {
letters.push(node.data);
});
for (let item of letters) {
console.log(item); //['a', 'b', 'd', 'c']
}
letters = [];
t.depth_first_search(node => {
letters.push(node.data);
});
for (let item of letters) {
console.log(item); //['a', 'b', 'c', 'd']
}