Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0c7834

Browse files
add delete method
1 parent 4cf6df8 commit d0c7834

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

‎data-structures/binary-search-tree.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,24 @@ BST.prototype.insert = function (value) {
2929
}
3030

3131
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+
}
3650
}
3751

3852
BST.prototype.transplant = function (u, v) {
@@ -79,9 +93,8 @@ BST.prototype.sucessor = function(value) {
7993

8094
BST.prototype.predecessor = function(value) {
8195
let current = this.search(value)
82-
if (current.left){
96+
if (current.left)
8397
return this.max(current.left)
84-
}
8598
while (current.parent && current === current.parent.left)
8699
current = current.parent
87100
return current.parent
@@ -131,5 +144,10 @@ test('BST', assert => {
131144
assert.deepEqual(bst.predecessor(12).key, 8)
132145
assert.deepEqual(bst.predecessor(8).key, 4)
133146
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)
134152
assert.end()
135153
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /