-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary search tree.js
71 lines (62 loc) · 1.63 KB
/
binary search tree.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
function bst() {
this.root = null;
}
bst.prototype.newnode = function(value) {
var node = {};
node.value = value;
node.left = null;
node.right = null;
return node;
};
bst.prototype.add = function(value) {
var current = this.newnode(value);
if (!this.root) {
this.root = current;
} else {
this.insert(current);
}
return this;
};
bst.prototype.insert = function(current) {
var value = current.value;
var find = function(node) {
if (value === node.value) {
return;
}else if (value > node.value) {
if (!node.right) {
node.right = current;
return;
} else
find(node.right);
} else if (value < node.value) {
if (!node.left) {
node.left = current;
return;
} else
find(node.left);
}
};
find(this.root);
};
bst.prototype.minimum = function() {
var node = this.root;
var find = function(node) {
return !node.left ? node.value : find(node.left);
};
return find(node);
};
bst.prototype.maximum = function() {
var node = this.root;
var find = function(node) {
return !node.right ? node.value : find(node.right);
};
return find(node);
};
bst.prototype.heightt = function(node) {
if(!node) return 0;
function height(node){
var leftHeight = height(node.left);
var rightHeight = height(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}