-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbst-map.js
81 lines (63 loc) · 1.54 KB
/
bst-map.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
(function(){
var Node = function (key, value) {
this.key = key;
this.value = value;
this.right = {};
this.left = {};
};
var BSTMap = function () {
var size = 0;
var bst;
this.get = function (key) {
if (this.size() === 0) return false;
var search = function (node) {
if (!node) return;
if (key === node.key) return node.value;
if (key < node.key) {
search(node.left);
} else {
search(node.right);
}
};
return search(bst) || false;
};
this.set = function (key, value) {
if (size === 0) {
bst = new Node(key, value);
}
if (!this.get(key)) size++;
var insearch = function (node) {
if (node.key === key) {
node.value = value;
return;
}
if (key < node.key) {
if (Object.keys(node.left).length === 0) {
node.left = new Node(key, value);
} else {
insearch(node.left);
}
} else {
if (Object.keys(node.right).length === 0) {
node.right = new Node(key, value);
} else {
insearch(node.right);
}
}
};
insearch(bst);
};
this.size = function () {
return size;
};
};
var root = this;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = BSTMap;
}
exports.BSTMap = BSTMap;
} else {
root.BSTMap = BSTMap;
}
})();