Skip to content

Commit d1b4a74

Browse files
m-maksyutinshoredata
authored andcommitted
Fix BST removal method (trekhleb#74)
* Fix LinkedList * Fix the prepend method for the LinkedList * Fix the remove method for the MinHeap * Correct a comment * Fix BST removal method
1 parent 51e4c6a commit d1b4a74

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

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

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,13 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
9494

9595
if (!nodeToRemove.left && !nodeToRemove.right) {
9696
// Node is a leaf and thus has no children.
97-
// Just remove the pointer to this node from the parent node.
98-
parent.removeChild(nodeToRemove);
97+
if (parent) {
98+
// Node has a parent. Just remove the pointer to this node from the parent.
99+
parent.removeChild(nodeToRemove);
100+
} else {
101+
// Node has no parent. Just erase current node value.
102+
nodeToRemove.value = null;
103+
}
99104
} else if (nodeToRemove.left && nodeToRemove.right) {
100105
// Node has two children.
101106
// Find the next biggest value (minimum value in the right branch)
@@ -113,11 +118,10 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
113118
} else {
114119
// Node has only one child.
115120
// Make this child to be a direct child of current node's parent.
116-
if (nodeToRemove.left) {
117-
parent.replaceChild(nodeToRemove, nodeToRemove.left);
118-
} else {
119-
parent.replaceChild(nodeToRemove, nodeToRemove.right);
120-
}
121+
const child = nodeToRemove.left || nodeToRemove.right;
122+
nodeToRemove.value = child.value;
123+
nodeToRemove.setLeft(child.left);
124+
nodeToRemove.setRight(child.right);
121125
}
122126

123127
return true;

src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,21 @@ describe('BinarySearchTreeNode', () => {
185185
expect(bstRootNode.toString()).toBe('30');
186186
});
187187

188+
it('should remove node with no parent', () => {
189+
const bstRootNode = new BinarySearchTreeNode();
190+
expect(bstRootNode.toString()).toBe('');
191+
192+
bstRootNode.insert(1);
193+
bstRootNode.insert(2);
194+
expect(bstRootNode.toString()).toBe('1,2');
195+
196+
bstRootNode.remove(1);
197+
expect(bstRootNode.toString()).toBe('2');
198+
199+
bstRootNode.remove(2);
200+
expect(bstRootNode.toString()).toBe('');
201+
});
202+
188203
it('should throw error when trying to remove not existing node', () => {
189204
const bstRootNode = new BinarySearchTreeNode();
190205

0 commit comments

Comments
 (0)