-2

I am trying to delete the right most node of a binary tree. I am using a function to find the right most node which is returning me the the right most node of Binary tree correctly and then I am assigning in the null value. But when I am printing the Binary tree the value of right most node is getting printed.Please help me understand why this is happening.

    void deleteNode(Node root, int Key)
{

    Node rightMost = rightmost(root); // returns the right most node
    rightMost = null

}

If I am deleting the link from parent node to the rightmost child then the node is getting deleted but not when I am making the node itself as null. This is confusing because if the node itself is null then it should get deleted.

1 Answers1

0

The tricky part is that Java is giving you essentially a pointer to the rightmost node, which you're then setting to null.

To explain:

Node rightMost = rightmost(root); // returns the right most node

rightMost is now a variable that just contains a memory address, for example 0x0123456. So when you say:

rightMost = null

What's actually happening is it's grabbing the node's rightmost address and copying it into this variable rightMost. You're then setting this copy to null instead of the actual underlying rightmost node.

Analogy: I may set John Smith in my contacts to have home address 1234 State Street. However, if I change John Smith's address in my contacts to 2345 Main Street, this doesn't actually cause John to move houses! I'm just updating my internal reference of where John's home is. Same thing here.

Java is definitely tricky because it's pass by value but the value is a reference. I highly recommend reading this and this.

To actually do what you're asking, you need to be able to access the underlying property and set it, something like this, where node is the parent of the rightmost node:

node.right = null

Or you can have some sort of setter that will set the rightmost node to a specified value. If you don't have any way to set the variable using a setter or direct access to the property, it's read-only from your point of view.

rb612
  • 5,280
  • 3
  • 30
  • 68