Fix BST removal method (#74)

* Fix LinkedList

* Fix the prepend method for the LinkedList

* Fix the remove method for the MinHeap

* Correct a comment

* Fix BST removal method
This commit is contained in:
m-maksyutin 2018-06-22 07:57:52 +03:00 committed by Oleksii Trekhleb
parent e558231474
commit bd5a16be71
2 changed files with 26 additions and 7 deletions

View File

@ -94,8 +94,13 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
if (!nodeToRemove.left && !nodeToRemove.right) { if (!nodeToRemove.left && !nodeToRemove.right) {
// Node is a leaf and thus has no children. // Node is a leaf and thus has no children.
// Just remove the pointer to this node from the parent node. if (parent) {
// Node has a parent. Just remove the pointer to this node from the parent.
parent.removeChild(nodeToRemove); parent.removeChild(nodeToRemove);
} else {
// Node has no parent. Just erase current node value.
nodeToRemove.value = null;
}
} else if (nodeToRemove.left && nodeToRemove.right) { } else if (nodeToRemove.left && nodeToRemove.right) {
// Node has two children. // Node has two children.
// Find the next biggest value (minimum value in the right branch) // Find the next biggest value (minimum value in the right branch)
@ -113,11 +118,10 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
} else { } else {
// Node has only one child. // Node has only one child.
// Make this child to be a direct child of current node's parent. // Make this child to be a direct child of current node's parent.
if (nodeToRemove.left) { const child = nodeToRemove.left || nodeToRemove.right;
parent.replaceChild(nodeToRemove, nodeToRemove.left); nodeToRemove.value = child.value;
} else { nodeToRemove.setLeft(child.left);
parent.replaceChild(nodeToRemove, nodeToRemove.right); nodeToRemove.setRight(child.right);
}
} }
return true; return true;

View File

@ -185,6 +185,21 @@ describe('BinarySearchTreeNode', () => {
expect(bstRootNode.toString()).toBe('30'); expect(bstRootNode.toString()).toBe('30');
}); });
it('should remove node with no parent', () => {
const bstRootNode = new BinarySearchTreeNode();
expect(bstRootNode.toString()).toBe('');
bstRootNode.insert(1);
bstRootNode.insert(2);
expect(bstRootNode.toString()).toBe('1,2');
bstRootNode.remove(1);
expect(bstRootNode.toString()).toBe('2');
bstRootNode.remove(2);
expect(bstRootNode.toString()).toBe('');
});
it('should throw error when trying to remove not existing node', () => { it('should throw error when trying to remove not existing node', () => {
const bstRootNode = new BinarySearchTreeNode(); const bstRootNode = new BinarySearchTreeNode();