javascript-algorithms icon indicating copy to clipboard operation
javascript-algorithms copied to clipboard

`replaceChild` method in BinaryTreeNode is not correct

Open le-huy-jh opened this issue 1 year ago • 1 comments

Missing update parent. It should be

    if (!nodeToReplace || !replacementNode) {
      return false;
    }

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

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

    return false;
  }

le-huy-jh avatar Jan 31 '24 16:01 le-huy-jh

explain(nodeToReplace, replacementNode) { if (!nodeToReplace || !replacementNode) { return false; }

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

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

// Add the following update to set the parent of replacementNode correctly
if (this.left && this.left.explain(nodeToReplace, replacementNode)) {
  return true;
}

if (this.right && this.right.explain(nodeToReplace, replacementNode)) {
  return true;
}

return false;

}

Prakash-2002 avatar Feb 05 '24 18:02 Prakash-2002