Hello, I have a method that looks for an element in a binary tree and the problem is that it behaves incredibly strange. When I went through the debager on it, it turned out that everything works exactly as I had in mind, but after going through the return line, the method does not finish the work, but begins to perform some more incomprehensible actions. It just breaks my understanding of how methods work.
Here is the code:
@Override public Leaf<E> find(E elem) { Leaf<E> eLeaf = new Leaf<>(elem); return binarySearch(root, eLeaf); } private Leaf<E> binarySearch(Leaf<E> leaf, Leaf<E> eLeaf) { int compare = leaf.compareTo(eLeaf); if (compare < 0 && leaf.right != null) { binarySearch(leaf.right, eLeaf); } if (compare > 0 && leaf.left != null) { binarySearch(leaf.left, eLeaf); } if (compare == 0) { return leaf; } return null; } To be precise, everything goes fine, but then it finds a match in place:
if (compare == 0) { return leaf; } Comes to the line return leaf; everything seems to be all ... The blue stripe of the debugger has gone to return , the debager prints the address of the object to me which will now return ... But no, all of a sudden it returns to the second if ! How is this possible? Does not writing return guarantee that the work of the method will be completed?