I wrote BST insertion code with the book. The book uses recursion, but I just want to know how I can do it without recursion.
My code is working, but I don't know if it is correct.
public class BSearchTree {
BNode root = null;
public void add(BNode node){
int depth = 0;
if(root != null){
if(node.data == root.data) return;
BNode p = root;
while(p != null){
depth++;
if(p.data < node.data){
if(p.right != null){
p = p.right;
}else{
p.right = node;
node.index = depth;
break;
}
}else{
if(p.left != null){
p = p.left;
}else{
p.left = node;
node.index = depth;
break;
}
}
}
}else{
root = node;
node.index = depth;
}
inOrder(root, "[ROOT]");
}
public void inOrder(BNode node, String direction){
BNode p = node;
if(p == null) return;
inOrder(p.left, "[LEFT]");
System.out.println(p.index+": "+direction+" "+p.data);
inOrder(p.right, "[RIGHT]");
}
}