0
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
|
const createNode = val => ({
val,
left: null,
right: null
})
const search = (node, val) => {
if (node === null) return null
else if (val === node.val) return node
else if (val < node.val) return search(node.left, val)
else if (val > node.val) return search(node.right, val)
}
const insertNode = (node, newNode) => {
if (newNode.val < node.val) {
if (node.left === null) {
node.left = newNode
} else insertNode(node.left, newNode)
} else {
if (node.right === null) {
node.right = newNode
} else insertNode(node.right, newNode)
}
}
const createBST = () => {
let root = null
return {
insert: function (val) {
const node = createNode(val)
if (root === null) root = node
else insertNode(root, node)
return this
},
find: val => search(root, val),
contains: val => search(root, val) != null,
delete: val => {
// todo
},
getTree: () => root
}
}
module.exports = createBST
|