trekhleb/javascript-algorithms

`replaceChild` method in BinaryTreeNode is not correct

le-huy-jh opened this issue · 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;
  }

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;

}