Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix BST removal method #74

Merged
merged 15 commits into from
Jun 22, 2018
Merged
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
@@ -94,8 +94,13 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {

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

return true;
Original file line number Diff line number Diff line change
@@ -185,6 +185,21 @@ describe('BinarySearchTreeNode', () => {
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', () => {
const bstRootNode = new BinarySearchTreeNode();