-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.js
119 lines (92 loc) · 1.86 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
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
112
113
114
115
116
117
118
119
const Search = require("../Search")
class Node {
#key
#value
#left
#right
#nodesCount
constructor(key, value, nodesCount) {
this.#key = key
this.#value = value
this.#nodesCount = nodesCount
}
get right() {
return this.#right
}
get left() {
return this.#left
}
get value() {
return this.#value
}
get nodesCount() {
return this.#nodesCount
}
get key() {
return this.#key
}
set value(value) {
this.#value = value
}
set right(right) {
this.#right = right
}
set left(left) {
this.#left = left
}
set nodesCount(nodesCount) {
this.#nodesCount = nodesCount
}
}
class BinarySearchTree extends Search {
#root
constructor() {
super()
this.#root = null
}
size() {
return this.nodeSize(this.#root)
}
nodeSize(node) {
if (!node) {
return 0
} else {
return node.nodesCount
}
}
get (key) {
return this.getNodeValue(this.#root, key)
}
getNodeValue (node, key) {
if (!node) {
return null
}
const comparison = this.compareValues(key, node.key)
if (comparison < 0) {
return this.getNodeValue(node.left, key)
} else if (comparison > 0) {
return this.getNodeValue(node.right, key)
} else {
return node.value
}
}
put (key, value) {
this.#root = this.putNodeValue(this.#root, key, value)
}
putNodeValue (node, key, value) {
if (!node) {
return new Node(key, value, 1)
}
const comparison = this.compareValues(key, node.key)
if (comparison < 0) {
node.left = this.putNodeValue(node.left, key, value)
} else if (comparison > 0) {
node.right = this.putNodeValue(node.right, key, value)
} else {
node.value = value
}
node.nodesCount = this.nodeSize(node.left) + this.nodeSize(node.right) + 1
return node
}
}
module.exports = BinarySearchTree