Skip to content

Commit da6f240

Browse files
Fix binarySearchTreeNode removing
1 parent 1503325 commit da6f240

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,10 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
101101
if (parent) {
102102
// Node has a parent. Just remove the pointer to this node from the parent.
103103
parent.removeChild(nodeToRemove);
104+
nodeToRemove.parent = null;
104105
} else {
105106
// Node has no parent. Just erase current node value.
106-
nodeToRemove.setValue(undefined);
107+
nodeToRemove.setValue(null);
107108
}
108109
} else if (nodeToRemove.left && nodeToRemove.right) {
109110
// Node has two children.
@@ -127,14 +128,13 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
127128

128129
if (parent) {
129130
parent.replaceChild(nodeToRemove, childNode);
131+
childNode.parent = parent;
132+
nodeToRemove.parent = null;
130133
} else {
131134
BinaryTreeNode.copyNode(childNode, nodeToRemove);
132135
}
133136
}
134137

135-
// Clear the parent of removed node.
136-
nodeToRemove.parent = null;
137-
138138
return true;
139139
}
140140

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,4 +252,30 @@ describe('BinarySearchTreeNode', () => {
252252

253253
expect(childNode.parent).toBeNull();
254254
});
255+
256+
it('should remove nodes 3,6 in tree 3,6,8', () => {
257+
const root = new BinarySearchTreeNode(8);
258+
259+
root.insert(3);
260+
root.insert(6);
261+
262+
root.remove(3);
263+
root.remove(6);
264+
265+
expect(root.right).toBeNull();
266+
expect(root.left).toBeNull();
267+
});
268+
269+
it('should remove nodes 8 in tree 6,8', () => {
270+
const root = new BinarySearchTreeNode(8);
271+
272+
root.insert(6);
273+
274+
root.remove(8);
275+
276+
expect(root.right).toBeNull();
277+
expect(root.left).toBeNull();
278+
expect(root.parent).toBeNull();
279+
expect(root.value).toBe(6);
280+
});
255281
});

0 commit comments

Comments
 (0)