diff --git a/src/data-structures/tree/BinaryTreeNode.js b/src/data-structures/tree/BinaryTreeNode.js index cca840da..1c3d2608 100644 --- a/src/data-structures/tree/BinaryTreeNode.js +++ b/src/data-structures/tree/BinaryTreeNode.js @@ -31,18 +31,36 @@ export default class BinaryTreeNode { } setLeft(node) { + // Reset parent for left node since it is going to be detached. + if (this.left) { + this.left.parent = null; + } + + // Attach new node to the left. this.left = node; - if (node) { + + // Make current node to be a parent for new left one. + if (this.left) { this.left.parent = this; } + return this; } setRight(node) { + // Reset parent for right node since it is going to be detached. + if (this.right) { + this.right.parent = null; + } + + // Attach new node to the right. this.right = node; + + // Make current node to be a parent for new right one. if (node) { this.right.parent = this; } + return this; }