-
Notifications
You must be signed in to change notification settings - Fork 21
/
bst.js
81 lines (68 loc) · 1.34 KB
/
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
80
81
// Binary Search Tree
BST = function () {
this.root = null;
};
BST.prototype.insert = function (v) {
if (this.root == null) {
this.root = new BST.Node(v);
} else {
this.root.insert(v);
}
};
BST.prototype.find = function (v) {
if (this.root == null) {
return false;
} else {
return this.root.find(v);
}
};
// Binary Search Tree Node
BST.Node = function (v) {
this.value = v;
this.left = null;
this.right = null;
};
BST.Node.prototype.insert = function (v) {
if (v < this.value) {
if (this.left == null) {
this.left = new BST.Node(v);
} else {
this.left.insert(v);
}
} else if (v > this.value) {
if (this.right == null) {
this.right = new BST.Node(v);
} else {
this.right.insert(v);
}
}
};
BST.Node.prototype.find = function (v) {
if (v < this.value) {
if (this.left == null) {
return false;
} else {
return this.left.find(v);
}
} else if (v > this.value) {
if (this.right == null) {
return false;
} else {
return this.right.find(v);
}
} else {
return true;
}
};
// function Main() {
// var t = new BST();
// t.insert(2);
// t.insert(1);
// t.insert(3);
// console.log(t);
// console.log(t.find(1));
// console.log(t.find(2));
// console.log(t.find(3));
// console.log(t.find(4));
// }
// Main();