Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,10 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
if (parent) {
// Node has a parent. Just remove the pointer to this node from the parent.
parent.removeChild(nodeToRemove);
nodeToRemove.parent = null;
} else {
// Node has no parent. Just erase current node value.
nodeToRemove.setValue(undefined);
nodeToRemove.setValue(null);
}
} else if (nodeToRemove.left && nodeToRemove.right) {
// Node has two children.
Expand All @@ -127,14 +128,13 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {

if (parent) {
parent.replaceChild(nodeToRemove, childNode);
childNode.parent = parent;
nodeToRemove.parent = null;
} else {
BinaryTreeNode.copyNode(childNode, nodeToRemove);
}
}

// Clear the parent of removed node.
nodeToRemove.parent = null;

return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,4 +252,30 @@ describe('BinarySearchTreeNode', () => {

expect(childNode.parent).toBeNull();
});

it('should remove nodes 3,6 in tree 3,6,8', () => {
const root = new BinarySearchTreeNode(8);

root.insert(3);
root.insert(6);

root.remove(3);
root.remove(6);

expect(root.right).toBeNull();
expect(root.left).toBeNull();
});

it('should remove nodes 8 in tree 6,8', () => {
const root = new BinarySearchTreeNode(8);

root.insert(6);

root.remove(8);

expect(root.right).toBeNull();
expect(root.left).toBeNull();
expect(root.parent).toBeNull();
expect(root.value).toBe(6);
});
});