Here is a piece of code in my algorithm:
public void insert(int element) {
_insert(element, root);
System.out.println(root);
}
private void _insert (int element, Node t) {
if (t == null) {
t = new Node(null, element);;
return;
}
}
Node here is a predefined class.
When the public method insert is called, the private method will be called and check if the tree is empty. If so, a new node would be created at root position.
The output is supposed to be a node. However the actual output is null which means root is not updated though it’s passed as t into the private method.
This should work under C++ with pointers. Maybe I misunderstand something in Java?
Java always uses pass-by-value for method calls. When you pass a reference type to a method, a copy of the reference is made.
The following line changes
tto refer to a new object, but it does not change the original variableroot:You can change your method to return the inserted node, as follows:
And call like this: