Nodes are inserted one after the other by the user.

2024-04-04 14-24-15.mkv (1.5 MB)

If you’re talking about threejs, then this shouldn’t happen. The scene graph is a directed, **acyclic** graph (dag). When you add a node to another node, it removes itself from its parent node if any, first, then adds it to the new node.

Thanks for replying . Here, i am visualizing binary tree(BST to be specific). I am finding it difficult to place the nodes in their proper location.

Node

```
class Node {
constructor(data) {
this.mesh = new THREE.Group();
this.left = null;
this.right = null;
this.data = data;
// create sphere and arrows
this.mesh.add(sphere, left_arrow, right_arrow);
}
```

Insert Method

```
insert(data) {
this.root = insertNode(this.root, data);
function insertNode(root, data, x = 0, y = 0, ) {
let node = new Node(data);
node.mesh.position.set(x, y, 0);
if (root == null) {
node.mesh.visible = true;
root = node;
return root;
}
if (data < root.data) {
root.left = insertNode(root.left, data, x - 2, y - 1.2);
} else if (data > root.data) {
root.right = insertNode(root.right, data, x + 2.3, y - 1.2);
}
return root;
}
}
```

see Generate coordinates for each node to display a complete binary tree?

*Available thanks to* @PavelBoytchev

2 Likes