-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.js
79 lines (65 loc) · 1.71 KB
/
tree.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
class Node {
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (this.root == null) {
this.root = newNode;
} else {
let currentNode = this.root;
while (true) {
if (value < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
return this;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = newNode;
return this;
}
currentNode = currentNode.right;
}
}
}
}
search(value, tree = this.root) {
if (tree == null) {
return "El elemento no se encuentra.";
}
else if (value > tree.value) {
return this.search(value, tree.right);
}
else if (value < tree.value) {
return this.search(value, tree.left);
}
else {
return "¡El elemento ha sido encontrado!";
}
}
}
const myTree = new BinarySearchTree();
console.log(myTree);
myTree.insert(10);
console.log(myTree);
myTree.insert(4);
myTree.insert(20);
console.log(myTree);
myTree.insert(2);
myTree.insert(8);
myTree.insert(17);
myTree.insert(170);
console.log(myTree);
// test search
console.log("***** search *****");
console.log(myTree.search(2));
console.log(myTree.search(200));