-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinarySearchTree.js
70 lines (61 loc) · 1.17 KB
/
BinarySearchTree.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
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
hasLeft() {
return this.left != null;
}
hasRight() {
return this.right != null;
}
getValue() {
return this.value;
}
}
class BinarySearchTree {
construct() {
this.root = null;
}
add(value) {
if(this.root == null) {
this.root = new Node(value);
} else {
let node = this.getNode(this.root, value);
if(node.value != value) {
let newNode = new Node(value);
if(value < node.value) {
node.left = newNode;
} else {
node.right = newNode;
}
}
}
}
getNode(node, value) {
if(value == node.value) {
return node;
} else {
if(value < node.value) {
if(node.hasLeft()) {
return this.getNode(node.left, value);
} else {
return node;
}
} else {
if(node.hasRight()) {
return getNode(node.right, value);
} else {
return node;
}
}
}
}
}
var t = new BinarySearchTree();
t.add(5);
t.add(2);
t.add(6);
t.add(4);
console.log(JSON.stringify(t, null, 2))