JSFiddle - React, Tailwind, and code Playground
by Vikram Deshmukh
HTML
<h4>
Yelp Interview Question
</h4>
<p>
Q. Write code to create a hierarchical tree given a list of (parent, child) pairs.</p>
<p>
Sample input:
const input = [
["Charlie", "Denis"],
["Alice", "Ben"],
["Ben", "Charlie"],
]
</p>
JavaScript
const input = [
["Charlie", "Denis"],
["Alice", "Ben"],
["Ben", "Charlie"],
]
class Node {
constructor(name) {
this.name = name;
this.reportees = [];
this._parent = null;
}
get rname () {
return this.name;
}
set parent (node) {
this._parent = node;
}
get parent () {
return this._parent;
}
addReportee (rName){
let node = getNode(rName);
node.parent = this;
this.reportees.push(node);
}
}
const map = [];
function getNode(name) {
let node = map[name];
if(!node) {
node = new Node(name);
map[name] = node;
}
return node;
}
function createTree(arr) {
let root = null;
arr.forEach(function(pair) {
let node = getNode(pair[0])
node.addReportee(pair[1]);
if(!root || root.rname === pair[1]) {
root = node;
while(root.parent != null) {
root = root.parent;
}
}
})
return root;
}
console.log(createTree(input));