I have found this Java recursive program for adding an element into a binary search tree:
public void add(int e){
root=add(root, e);
}
public Node add(Node n, int e){
if (n==null){
n=new Node(e);
} else {
if (e<n.elem){
n.left=add(n.left,e);
} else{
n.right=add(n.right,e);
}
}
return n;
}
What I do not understand is why it has to return n at the end and then assign it to root again.
return nstatement at the end is called after the recursive calls to the left and right have finished. You should review a tutorial (or textbook) covering recursion.rootrefers to the actual tree root only on the first call. After that, as you get more than one level down,rootrefers to the root of the current subtree.