-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
111 lines (94 loc) · 2.58 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
insert(value) {
if (!this.root) {
this.root = new TreeNode(value);
} else {
this._insertRec(this.root, value);
}
}
_insertRec(node, value) {
if (value < node.value) {
if (node.left) {
this._insertRec(node.left, value);
} else {
node.left = new TreeNode(value);
}
} else {
if (node.right) {
this._insertRec(node.right, value);
} else {
node.right = new TreeNode(value);
}
}
}
}
const tree = new BinaryTree();
const treeContainer = document.getElementById("treeContainer");
function getContainerWidth() {
return treeContainer.getBoundingClientRect().width;
}
function clearTree() {
tree.root = null;
treeContainer.innerHTML = '';
}
function addNode() {
const value = parseInt(document.getElementById("nodeValue").value);
if (isNaN(value)) {
alert("Please enter a valid number.");
return;
}
tree.insert(value);
document.getElementById("nodeValue").value = "";
redrawTree();
}
function redrawTree() {
treeContainer.innerHTML = '';
visualizeTree(tree.root, 0.5, 50, 0.5, 0);
}
function drawLine(x1, y1, x2, y2) {
const line = document.createElement("div");
line.classList.add("line");
const length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
line.style.width = `${length}px`;
line.style.left = `${x1}px`;
line.style.top = `${y1}px`;
line.style.transform = `rotate(${angle}deg)`;
treeContainer.appendChild(line);
}
function visualizeTree(node, x, y, parentX, parentY) {
if (!node) return;
const containerWidth = getContainerWidth();
const nodeX = x * containerWidth;
const parentNodeX = parentX * containerWidth;
const nodeElement = document.createElement("div");
nodeElement.classList.add("node");
nodeElement.style.left = `${nodeX}px`;
nodeElement.style.top = `${y}px`;
nodeElement.innerText = node.value;
if (y > 50) {
drawLine(parentNodeX, parentY, nodeX, y);
}
treeContainer.appendChild(nodeElement);
const level = Math.floor(y / 60);
const spacing = 0.15 / (level + 1);
const verticalSpacing = 60;
visualizeTree(node.left, x - spacing, y + verticalSpacing, x, y);
visualizeTree(node.right, x + spacing, y + verticalSpacing, x, y);
}
const resizeObserver = new ResizeObserver(() => {
if (tree.root) {
redrawTree();
}
});
resizeObserver.observe(treeContainer);