From 4d8d6e0797e707ef193eb276e6470d4cc47e8cb5 Mon Sep 17 00:00:00 2001 From: DeoJin <268571697+DeoJin@users.noreply.github.com> Date: Tue, 17 Mar 2026 11:52:45 +0100 Subject: [PATCH] fix: preserve parent when replacing binary tree child --- src/data-structures/tree/BinaryTreeNode.js | 4 ++-- src/data-structures/tree/__test__/BinaryTreeNode.test.js | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/data-structures/tree/BinaryTreeNode.js b/src/data-structures/tree/BinaryTreeNode.js index 44c9390e41..e8ff03aeee 100644 --- a/src/data-structures/tree/BinaryTreeNode.js +++ b/src/data-structures/tree/BinaryTreeNode.js @@ -166,12 +166,12 @@ export default class BinaryTreeNode { } if (this.left && this.nodeComparator.equal(this.left, nodeToReplace)) { - this.left = replacementNode; + this.setLeft(replacementNode); return true; } if (this.right && this.nodeComparator.equal(this.right, nodeToReplace)) { - this.right = replacementNode; + this.setRight(replacementNode); return true; } diff --git a/src/data-structures/tree/__test__/BinaryTreeNode.test.js b/src/data-structures/tree/__test__/BinaryTreeNode.test.js index 8eeda4dda5..3b5d485c6e 100644 --- a/src/data-structures/tree/__test__/BinaryTreeNode.test.js +++ b/src/data-structures/tree/__test__/BinaryTreeNode.test.js @@ -91,6 +91,7 @@ describe('BinaryTreeNode', () => { expect(rootNode.replaceChild(rootNode.right, rootNode.right.right)).toBe(true); expect(rootNode.right.value).toBe(5); + expect(rootNode.right.parent).toEqual(rootNode); expect(rootNode.right.right).toBeNull(); expect(rootNode.traverseInOrder()).toEqual([1, 2, 5]);