I'm new to understanding and learning data structures.I have tried to implement Tree data structure after searching some tutorials.It seems well but i don't understand the recursive behavior which was a bit strange here.Can someone help me in understanding the code.
I have included some print statements to understand the recursive flow but was not able to understand why the current refernce is not being returned?
public class TreeCheck {
Node root;
private Node addRecursive(Node current, int value) {
if (current == null) {
return new Node(value);
}
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
System.out.println("current is "+current.value); //Please compare in the
image why the
return current;
}
public void add(int value) {
root = addRecursive(root, value);
System.out.println("value is "+root.value);
}
public static void main(String h[]){
TreeCheck bt = new TreeCheck();
bt.add(6);
bt.add(4);
bt.add(8);
bt.add(3);
bt.add(5);
bt.add(7);
bt.add(9);
}
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
right = null;
left = null;
}
}
Why the current statement is being printed twice and always returns the root element only when the current is re-assigned sometimes?

println("START: current is" + ...), and one where the current log isprintln("END: current is" + ...). Maybe even add some more logs in your if-Statements to clearly see if it's added to the left or the right of the tree. An even better approach would be to take a pen and paper and draw the tree step by step to see how it is created.