-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Closed
Description
My fix for #46 explained here #47 was a 'woosh'. If root has children, with that change in place, they just become orphans and are lost in the void (rip).
if (node._parent !== null) {
if (node._left) {
this._replaceChild(node._parent, node, node._left);
} else if (node._right) {
this._replaceChild(node._parent, node, node._right);
} else {
this._replaceChild(node._parent, node, null);
}
}else {
this._root = null; // all children of that node lost in void
}So I've removed the code from #47 and have a new fix that isn't stupid, tested, and works.
exports.BinaryTree.prototype._replaceChild =
function (parent, oldChild, newChild) {
if (!parent) {
this._root = newChild;
if(this._root !== null){ //ADDED
this._root._parent = null;
} //ADDED
} else {
if (parent._left === oldChild) {
parent._left = newChild;
} else {
parent._right = newChild;
}
if (newChild) {
newChild._parent = parent;
}
}
};The new test - root removal with children:
it('should remove root and replace with valid child (1)', function () {
var bTree = new BinaryTree();
bTree.insert(15);
bTree.insert(30);
bTree.insert(45);
var node = bTree.find(15);
bTree.remove(node);
expect(bTree._root.value).toBe(30);
});will submit PR after #51 is handled (on same branch again 👯)
I'm going to be adding a bunch of tests to prevent these joys ![]()
Metadata
Metadata
Assignees
Labels
No labels