-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinarySearchTree.js
More file actions
64 lines (58 loc) · 1.42 KB
/
BinarySearchTree.js
File metadata and controls
64 lines (58 loc) · 1.42 KB
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
function Node(data) {
this.data = data;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.head = null;
this.insertNode = function(data) {
let newNode = data;
if(!(data instanceof Node)) {
newNode = new Node(data);
}
function traverse(node) {
if(node.data > data) {
if(!node.left) {
node.left = newNode;
return;
} else {
traverse(node.left);
}
} else {
if(!node.right) {
node.right = newNode;
return;
} else {
traverse(node.right);
}
}
}
if(!this.head) {
this.head = newNode;
} else {
traverse(this.head);
}
}
this.findNode = function(data) {
if(!this.head) {
return null;
}
function traverse(node) {
if(!node) {
return null;
}
if(node.data === data) {
return node;
} else if(node.data > data) {
return traverse(node.left);
} else {
return traverse(node.right);
}
}
return traverse(this.head);
}
}
module.exports = {
Node,
BinarySearchTree
}