[Solved] Recursion java return with some tree strcuture


To answer your question, yes it would make a huge difference if you removed the return statement from your return children.get(i).search(x); line of code.

The method signature:

public Node search(int x)

specifically states that it will return a node value, therefore the end result of this method must return a Node, or a null value.

“How does java handle these statements differently?”

The method call: children.get(i).search(x); merely runs the method and moves on. This only works if the method has a void return type. Since your method returns a value (in this case a Node) you have to do something with the value.

Calling a method that returns a value is like using a variable in a sense.

You can’t just have a line of code that says: variableX;

You need to do something with it. In your case, since your method returns a Node type, you’ve got to do something with the returned value when you call the method.

In order for this algorithm to work, you’re taking the value obtained from the called method, and returning it back to the calling method.

Using a visual example:

Search1 > Search2 > Search3

  • Search1 calls Search2,
  • Search2 calls Search3
  • Search3 returns a Node to Search2
  • Search2 returns that node to Search1

Removing the return key word will only give you errors since you would then have a line of code that amounts to a variable without doing anything with it.

children.get(i).search(x);

Would evaluate to a Node, which you must use.

solved Recursion java return with some tree strcuture