-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
82 lines (68 loc) · 2.32 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
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return this;
}
let current = this.root;
while (true) {
if (value === current.value) return undefined;
if (value < current.value) {
if (!current.left) {
current.left = newNode;
return this;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
return this;
}
current = current.right;
}
}
}
}
function buildTree() {
const inputNumbers = document.getElementById('inputNumbers').value;
const numbersArray = inputNumbers.split(',').map(Number);
const tree = new BinarySearchTree();
numbersArray.forEach(number => tree.insert(number));
const treeContainer = document.getElementById('treeContainer');
treeContainer.innerHTML = ''; // Clear previous tree
displayTree(tree.root, treeContainer);
}
function displayTree(node, container) {
if (node) {
const nodeElement = document.createElement('div');
nodeElement.className = 'node';
nodeElement.textContent = node.value;
const childrenContainer = document.createElement('div');
childrenContainer.className = 'children';
if (node.left) {
const leftContainer = document.createElement('div');
leftContainer.className = 'left';
displayTree(node.left, leftContainer);
childrenContainer.appendChild(leftContainer);
}
if (node.right) {
const rightContainer = document.createElement('div');
rightContainer.className = 'right';
displayTree(node.right, rightContainer);
childrenContainer.appendChild(rightContainer);
}
nodeElement.appendChild(childrenContainer);
container.appendChild(nodeElement);
}
}