-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST_remove
More file actions
57 lines (57 loc) · 1.19 KB
/
Copy pathBST_remove
File metadata and controls
57 lines (57 loc) · 1.19 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
BST.prototype.Remove = function(node){
if(!this.root || node == undefined){
return -1;
}
if(!(node instance of Node)){
node = new Node(node);
}
var current = this.root;
var parent = current;
while(current.value != node.value){
if (current.value < node.value){
parent = current;
current = current.right;
}
else{
parent = current;
current = current.left;
}
}
if (current.value != node.value){
return -1;
}
if (!current.left && !current.right){
if (current.value < parent.value){
parent.left = null;
}
else{
parent.right = null;
}
}
if (current.left){
var runner = current.left;
var papa = current;
while (runner.right){
papa = runner;
runner = runner.right;
}
else{
var runner = current.right;
var papa = current;
while (runner.left){
papa = runner;
runner = runner.left;
}
}
}
var temp = current;
current = runner;
runner = temp;
if(current.value < papa.value){
papa.left = null;
}
else{
papa.right = null;
}
return runner
}