Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions src/data-structures/tree/BinaryTreeNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,13 @@ export default class BinaryTreeNode {

if (this.left && this.nodeComparator.equal(this.left, nodeToReplace)) {
this.left = replacementNode;
replacementNode.parent = this;
return true;
}

if (this.right && this.nodeComparator.equal(this.right, nodeToReplace)) {
this.right = replacementNode;
replacementNode.parent = this;
return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import BinarySearchTree from '../BinarySearchTree';
import BinarySearchTreeNode from '../BinarySearchTreeNode';

describe('BinarySearchTree', () => {
it('should create binary search tree', () => {
Expand Down Expand Up @@ -52,6 +53,28 @@ describe('BinarySearchTree', () => {
expect(removed2).toBe(true);
});

it('should keep parent pointers consistent when removing a node with one child (issue #2102)', () => {
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 re-parent the surviving child via replaceChild (issue #1102)', () => {
const bst = new BinarySearchTree();
bst.insert(10);
bst.insert(5);
bst.insert(3);
const node5 = bst.root.left;
bst.remove(5);
expect(bst.root.left.value).toBe(3);
expect(bst.root.left.parent).toBe(bst.root);
expect(node5.parent).toBeNull();
});

it('should insert object values', () => {
const nodeValueCompareFunction = (a, b) => {
const normalizedA = a || { value: null };
Expand Down