Adding a node to a Binary Search Tree and printing the path to it 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 &lt; 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]");
    }
}
if(root != null){
        if(node.data == root.data) return;

        BNode p = root;

        while(p != null){


p cannot be null on the first pass.

Convert your while-loop into a do-while loop.

            }else{
                if(p.left != null){
                    p = p.left;
                }else{
                    p.left = node;
                    node.index = depth;
                    break;
                }
            }


else block containing only a if-elseif chain.

Merge them, like so:

            }else if(p.left != null){
                p = p.left;
            }else{
                p.left = node;
                node.index = depth;
                break;
            }