-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTree.js
54 lines (47 loc) · 1.4 KB
/
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
function BinarySearchTree(){
this.root = null;
}
BinarySearchTree.prototype.insert = function(val){
var root = this.root;
if(!root){
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
}else{
currentNode = currentNode.left;
}
}else{
if(!currentNode.right){
currentNode.right = newNode;
break;
}else{
currentNode = currentNode.right;
}
}
}
}
BinarySearchTree.prototype.remove = function (value) {
this.root = this._removeInner(value, this.root);
}
BinarySearchTree.prototype._removeInner = function (value, node) {
if (node) {
if (value < node.value) {
node.left = this._removeInner(value, node.left);
} else if (value > node.value) {
node.right = this._removeInner(value, node.right);
} else if (node.left && node.right) {
node.value = this.findMinValue(node.right);
node.right = this._removeInner(node.value, node.right);
} else {
node = node.left || node.right;
}
}
return node;
}