Skip to content

Commit 6613e2d

Browse files
committed
BST remove root with children bug fix.
1 parent ab55692 commit 6613e2d

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

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

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,9 @@
225225
function (parent, oldChild, newChild) {
226226
if (!parent) {
227227
this._root = newChild;
228-
this._root._parent = null;
228+
if (this._root !== null){
229+
this._root._parent = null;
230+
}
229231
} else {
230232
if (parent._left === oldChild) {
231233
parent._left = newChild;
@@ -251,25 +253,19 @@
251253
if (!node) {
252254
return false;
253255
}
254-
255256
if (node._left && node._right) {
256257
var min = this._findMin(node._right);
257258
var temp = node.value;
258-
259259
node.value = min.value;
260260
min.value = temp;
261261
return this.remove(min);
262262
} else {
263-
if (node._parent !== null) {
264-
if (node._left) {
265-
this._replaceChild(node._parent, node, node._left);
266-
} else if (node._right) {
267-
this._replaceChild(node._parent, node, node._right);
268-
} else {
269-
this._replaceChild(node._parent, node, null);
270-
}
271-
}else {
272-
this._root = null;
263+
if (node._left) {
264+
this._replaceChild(node._parent, node, node._left);
265+
} else if (node._right) {
266+
this._replaceChild(node._parent, node, node._right);
267+
} else {
268+
this._replaceChild(node._parent, node, null);
273269
}
274270
return true;
275271
}

test/data-structures/binary-search-tree.spec.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ describe('Binary Tree', function () {
2424
bTree.remove(node);
2525
expect(bTree._root).toBe(null);
2626
});
27+
it('should remove root and replace with valid child', function () {
28+
var bTree = new BinaryTree();
29+
bTree.insert(15);
30+
bTree.insert(30);
31+
bTree.insert(45);
32+
var node = bTree.find(15);
33+
bTree.remove(node);
34+
expect(bTree._root.value).toBe(30);
35+
});
2736
it('should insert multiple nodes properly', function () {
2837
var bTree = new BinaryTree();
2938
bTree.insert(10);

0 commit comments

Comments
 (0)