Skip to content

replaceChild method in BinaryTreeNode is not correct #1102

Open

Description

@le-huy-jh

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;
  }

Activity

  1. Prakash-2002 commented on Feb 5, 2024

    @Prakash-2002

    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;
    

    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions