trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings
MIT License
184.97k stars 29.83k forks source link

`replaceChild` method in BinaryTreeNode is not correct #1102

Open le-huy-jh opened 5 months ago

le-huy-jh commented 5 months ago

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;
  }
Prakash-2002 commented 4 months ago

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;

}