On the internet, there is tons of information on this topic. What is a tree data structure, why is it important, when do we need to use, etc. But there isn't a lot of places where you can find a js example on this topic. I will attach this example here. It can be also useful for me in the future. I've implemented it in an OOP way, hope anyone can understand it.
class Tree {
constructor(value) {
this.value = value;
this.right = null;
this.left = null;
}
addNode(value) {
return {
value,
right: null,
left: null
}
}
addValue(value) {
if (value === this.value) return;
let current = this;
while(current.value) {
if (current.value < value) {
if (current.right) {
current = current.right
}else {
current.right = this.addNode(value)
break;
}
}else {
if (current.left) {
current = current.left
}else {
current.left = this.addNode(value)
break;
}
}
}
}
}
const tree = new Tree(20);
tree.addValue(10)
tree.addValue(20)
tree.addValue(40)
tree.addValue(25)
tree.addValue(14)
console.log(tree)
Response:
{
value: 20,
right: {
value: 40,
right: null,
left: {
value: 25,
right: null,
left: null
}
},
left: {
value: 10,
right: {
value: 14,
right: null,
left: null
},
left: null
}
}