@@ -29,10 +29,24 @@ BST.prototype.insert = function (value) {
29
29
}
30
30
31
31
BST . prototype . delete = function ( value ) {
32
- // Need help with this one
33
- // What would be a good implementation:
34
- // All these methods in the Node object
35
- // or in the Tree object?
32
+ let current = this . search ( value )
33
+
34
+ if ( ! current . left )
35
+ this . transplant ( current , current . right )
36
+ else if ( ! current . right )
37
+ this . transplant ( current , current . left )
38
+ else {
39
+ let y = this . min ( current . right )
40
+
41
+ if ( y . parent !== current ) {
42
+ this . transplant ( y , y . right )
43
+ y . right = current . right
44
+ y . right . parent = y
45
+ }
46
+ this . transplant ( current , y )
47
+ y . left = current . left
48
+ y . left . parent = y
49
+ }
36
50
}
37
51
38
52
BST . prototype . transplant = function ( u , v ) {
@@ -79,9 +93,8 @@ BST.prototype.sucessor = function(value) {
79
93
80
94
BST . prototype . predecessor = function ( value ) {
81
95
let current = this . search ( value )
82
- if ( current . left ) {
96
+ if ( current . left )
83
97
return this . max ( current . left )
84
- }
85
98
while ( current . parent && current === current . parent . left )
86
99
current = current . parent
87
100
return current . parent
@@ -131,5 +144,10 @@ test('BST', assert => {
131
144
assert . deepEqual ( bst . predecessor ( 12 ) . key , 8 )
132
145
assert . deepEqual ( bst . predecessor ( 8 ) . key , 4 )
133
146
assert . deepEqual ( bst . predecessor ( 4 ) , null )
147
+ bst . delete ( 12 )
148
+ assert . deepEqual ( bst . search ( 12 ) , null )
149
+ assert . deepEqual ( bst . toArray ( ) , [ 4 , 8 , 15 ] )
150
+ assert . deepEqual ( bst . root . left . parent . key , 15 )
151
+ assert . deepEqual ( bst . length ( ) , 3 )
134
152
assert . end ( )
135
153
} )
0 commit comments