-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinarySearchTree.js
114 lines (97 loc) · 1.8 KB
/
BinarySearchTree.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
'use strict'
const BinaryTree = require("./BinaryTree");
module.exports = class BinarySearchTree extends BinaryTree{
add(value){
let c = this._root, p = null, n = BinaryTree.Node(value);
if(!c){
this._root = n;
return this;
}
_insert(c, p, n);
return this;
}
delete(value){
let cur = this._root, parent = null;
while(cur){
if(value === cur.val){
break;
}else if(value < cur.val){
parent = cur;
cur = cur.left;
}else{
parent = cur;
cur = cur.right;
}
}
if(!cur)
return false;
let isLeft = parent && parent.left === cur;
if(!cur.right){// has no right sub-tree
if(!parent){
this._root = cur.left;
}else if(isLeft){
parent.left = cur.left;
}else{
parent.right = cur.left;
}
}else if(!cur.right.left){
if(!parent){
this._root = cur.right;
cur.right.left = cur.left;
}else if(isLeft){
parent.left = cur.right;
}else{
parent.right = cur.right;
}
}else{
let n = cur.right.left, pp = cur.right;
while(n.left){
pp = n;
n = n.left;
}
pp.left = null;
if(!parent){
this._root = n;
n.right = cur.right;
n.left = cur.left;
}else if(isLeft){
parent.left = n;
n.left = cur.left;
n.right = cur.right;
}else{
parent.right = n;
n.left = cur.left;
n.right = cur.right;
}
}
}
has(value){
let cur = this._root;
while(cur){
if(value === cur.val){
return true;
}else if(value < cur.val){
cur = cur.left;
}else if(value > cur.val){
cur = cur.right;
}
}
return false;
}
}
function _insert(c, p, n){
if(!c){
if(n.val < p.val){
p.left = n;
}else{
p.right = n;
}
return;
}
if(n.val < c.val){
_insert(c.left, c, n);
}else if(n.val > c.val){
_insert(c.right, c, n);
}
// discard the duplicate value
}