I have been trying to simulate a BST using html css and JS. My goal to build it using animations, the problem is that when I add two nodes that are very close, they overlap each other. Currently I am adding the spaces between nodes using a constant, but I think I should do it by some calculation using the space between nodes.
const $btn = document.querySelector(".inputBtn")
const Xmovement = 15
const Ymovement = 20
class Node{
constructor(value){
this.value =value
this.left = null
this.right = null
this.xPos = 50
this.yPos = 30
}
printNode(){
const node = document.createElement("div")
node.className = "node"
node.textContent = this.value
document.body.appendChild(node)
node.style.backgroundColor = "red"
node.style.left = this.xPos + "%"
node.style.top = this.yPos + "%"
}
}
class Tree{
constructor(){
this.root = null
}
addNode(value){
const node = new Node(value)
if(!this.root){
this.root = node
node.printNode()
}
else{
this._addNode(this.root,node)
node.printNode()
}
}
_addNode(curr,node){
if(curr.value > node.value){
if(!curr.left ){
curr.left = node
node.xPos = curr.xPos-Xmovement
node.yPos = curr.yPos+Ymovement
}
else this._addNode(curr.left, node)
}
else if(curr.value < node.value){
if(!curr.right ){
curr.right = node
node.xPos = curr.xPos+Xmovement
node.yPos = curr.yPos+Ymovement
}
else this._addNode(curr.right, node)
}
return
}
addMany(nodes){
for(let node of nodes){
this.addNode(node)
}
}
inOrder(node){
if(node){
this.inOrder(node.left)
console.log(node.value)
this.inOrder(node.right)
}
}
}
const tree = new Tree
$btn.addEventListener("click", (ev)=>{
const $inputText = document.querySelector(".inputText").value
const nums = $inputText.split(",").map(el=>parseInt(el))
tree.addMany(nums)
tree.inOrder(tree.root)
})
My main idea was to calculate if there are two nodes on both levels that are inside the tree and to reduce the space by which they must be separated. but yeah