I ran into a perplex situation while I was trying to understand the binary search tree. I am baffled by the way the method recursion is happening here when a method is called, say inOrder(). Below is the code:
public class Node {
int data;
Node left;
Node right;
public Node (int data) {
this.data = data;
left = null;
right = null;
}
public Node() {
left = null;
right = null;
}
public int getData() {
return data;
}
}
====================
public class BinarySearch {
Node root;
public BinarySearch() {
root = null;
}
public void insert(int data) {
Node newNode = new Node();
newNode.data = data;
if(root == null) {
root = newNode;
System.out.println("root =" + root.getData());
} else {
Node current = root;
Node parent;
while(true) {
parent = current;
if(data < current.data) {
current = current.left;
if(current == null){
parent.left = newNode;
break;
}
} else {
current = current.right;
if(current == null) {
parent.right = newNode;
break;
}
}
}
}
}
public void inOrder() {
inOrder(root);
}
private void inOrder(Node n) {
if(n != null) {
inOrder(n.left);
System.out.print(n.getData() + " ");
inOrder(n.right);
}
}
}
===================
public class BTree {
public static void main(String[] args) {
BinarySearch bst = new BinarySearch();
bst.insert(10);
bst.insert(4);
bst.insert(11);
bst.inOrder();
}
}
o/p:
root = 10
4 10 11
Pardon me for the lengthy code, but I hoped you will need it complete.
When the inOrder() method is called, the compiler moves to the extreme left until Node n becomes null and exits the method based on the if statement, however, the immediate step the compiler is looking for after the if for false is System.out.print(n.getData() + " "); which is again inside the 'if' statement - This functionality amuses me a lot. I mean,
1) How is the compiler going to the line System.out.print when the if boolean is still false(because Node n is null) ?
2) Even if it goes to the print, how does n.getData() has a value(o/p: 4) when Node n actually reduced to null?
Thanks ahead!