In a Java file, I have the following code:
MyTree atree = new MyTree();
atree.insert(1);
This is not a regular tree. “atree” is the root node. Every node in this tree has 5 children, all initially set to null. The parameter for insert is the child that you want to ‘activate’, that is, make it non-null. So I have a method in the MyTree class that does this:
public void insert(int i)
{
if(i == 1)
{
MyTree current = this.getChildOne();
current = new MyTree();
}
}
After I call the function, I check the first node in the file where I called it.
if(atree.getChildOne() == null)
{
return -1;
}
And it always returns negative one. I suspect that the insert function is actually working on a copy of ‘atree’ and not the actual ‘atree’. But I am not entirely sure. Anyone have an explanation?
It doesn’t look like you are assigning child one anywhere. The code
does not assign child one. You initialize a local variable
currentbut then that variable is lost when the method ends.I think you probably want to do something like this in your insert method