-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01-bst.js
79 lines (66 loc) · 1.57 KB
/
01-bst.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 (val) {
this.val = val;
this.left = this.right = null;
}
}
class BinarySearchTree {
constructor () {
this.root = null;
}
insert (val, node = this.root) {
if (!this.root) {
this.root = new Node(val);
return this;
}
if (val === node.val) {
return -1;
}
if (val < node.val) {
if (!node.left) {
node.left = new Node(val);
return this;
}
return this.insert(val, node.left);
} else {
if (!node.right) {
node.right = new Node(val);
return this;
}
return this.insert(val, node.right);
}
}
find (val, node = this.root) {
if (!node) {
return -1;
}
if (node) {
if (val === node.val) {
return true;
}
if (val < node.val) {
if (node.left) {
return this.find(val, node.left);
}
} else {
if (node.right) {
return this.find(val, node.right);
}
}
}
return -1;
}
}
const bst = new BinarySearchTree();
bst.insert(3);
bst.insert(2);
bst.insert(5);
bst.insert(8);
bst.insert(1);
console.log(bst.find(3));
console.log(bst.find(2));
console.log(bst.find(5));
console.log(bst.find(8));
console.log(bst.find(1));
console.log(bst.find(99));
console.log(JSON.stringify(bst, 1));