Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active July 27, 2018 18:52
Show Gist options
  • Save GreggSetzer/82343f6f9783bb52451fbdbe71c8386f to your computer and use it in GitHub Desktop.
Save GreggSetzer/82343f6f9783bb52451fbdbe71c8386f to your computer and use it in GitHub Desktop.
JavaScript Interview Question: Tree
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 => node.data !== data);
}
}
class Tree {
constructor() {
this.root = null;
}
//Example of traversing breadth first.
traverseBF(fn) {
let arr = [this.root];
while (arr.length) {
const node = arr.shift();
arr.push(...node.children);
fn(node);
}
}
//Example of traversing depth first.
traverseDF(fn) {
let arr = [this.root];
while (arr.length) {
const node = arr.shift();
arr.unshift(...node.childen);
fn(node);
}
}
}
function levelWidth(root) {
const counters = [0];
const arr = [root, null];
while (arr.length > 1) {
const node = arr.shift();
if (node) {
arr.push(...node.children);
counters[counters.length - 1]++;
} else {
counters.push(0);
arr.push(null);
}
}
return counters;
}
(() => {
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');
t.traverseBF(node => {
letters.push(node.data);
});
expect(letters).toEqual(['a', 'b', 'c', 'd']);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment