diff --git a/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js b/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js index 314f8e06b8..35d567d628 100644 --- a/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js +++ b/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js @@ -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. @@ -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; } diff --git a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js index c9a2b6e0e1..86cc8e2ecd 100644 --- a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js +++ b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js @@ -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); + }); });