Data changing issue

64 views Asked by At

I have recently been studying binary search tree and their implementation in java. However my question is more related to obj. oriented programming more than data structures. One of the methods of the class binary tree is implemented as follow:

 protected BinaryNode<AnyType> findMin( BinaryNode<AnyType> t )
 { 

    //BinaryNode<AnyType> k= new BinaryNode<AnyType>(x);
    if( t != null )
        while( t.left != null )
        {   
             t=t.left;


        }
    return t;
}

Now if instead of "t" i put the "root" the minimimum element of the binary tree is returned, but at the end doesn't this method alter the value of the "root"? Actually I know that it doesn't change it, but i don't understand why.

5

There are 5 answers

0
Raman Shrivastava On

You don't want to change the actual value of root, that is why you use t. And call the method passing root. Root remain unchanged and t does all the work.

1
Roel Strolenberg On

Nothing changes to the tree. the t is a temporary replacement for whatever node you insert into the method. It's the same as when you would do this:

int x = 5;
int y = x + 1;
System.out.println(x);
System.out.println(y);

The output will still be:

5

6

0
iullianr On

The method alters the value of the method parameter from the stack and that value is a reference. So you alter the reference (which means is pointing to something else, some other memory area), not the value pointed by the reference (not the content of that memory area).

6
Alp On

I think this method is poorly named. What this method does is that it iterates through left nodes until it reaches a left most leaf and then it returns it. __Update__ Second thought: Actually the left most leaf is the min node of the tree. So it makes sense. My bad.

You should not want to change the root of the tree. That's your entry point. On the opposite, you want to remember it. If it a balanced tree, it sort of holds the mid point (or center of weight) of the tree. So it is important.

0
Turbero On

When you call a method in java, you pass the object by reference to a new variable, called "t" in your method findMin. You are changing the reference of "t" in your while block, that's all. But not your tree root node.

Take this as a little test:

public class RefTest {

    static String nameM2 = "Italy";

    public static void main(String[] args) {

        String nameM = "Spain", nameF = "France";

        System.out.println(nameM+", "+nameF);
        change(nameM);
        System.out.println(nameM+", "+nameF);
    }

    private static void change(String param) {
        param = nameM2;
    }
}

If you launch it, this is NOT the output:

Spain, France
Italy, France

Instead, this is:

Spain, France
Spain, France

Because you changed the reference in the param object, but it is never used again after getting out of change method.