-
Notifications
You must be signed in to change notification settings - Fork 2
/
binarySearchTree.js
68 lines (64 loc) · 1.42 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
class Node{
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(value){
// if no root assign value as root
// decide left or right
// if no left or right, assign it as left or right node
if(!this.root){
this.root = new Node(value);
return this;
}
let node = this.root;
while(node){
if(value === node.value) return undefined;
if(value<node.value){
if(!node.left){
node.left = new Node(value);
return this;
}
node = node.left;
}
else {
if(!node.right){
node.right = new Node(value);
return this;
}
node = node.right;
}
}
}
find(value){
if(!this.root) return null;
let node = this.root;
while(node){
if(value === node.value) return true;
if(value < node.value){
node = node.left;
} else {
node = node.right;
}
}
return false;
}
}
const tree = new BinarySearchTree();
tree.insert(10);
tree.insert(15);
tree.insert(7);
tree.insert(3);
tree.insert(25);
tree.insert(2);
console.log('--tree--', tree);
// console.log('--tree.find(2)--', tree.find(2));
// console.log('--tree.find(15)--', tree.find(15));
// console.log('--tree.find(1)--', tree.find(1));
// console.log('--tree.find(49)--', tree.find(49));