Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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]");
    }
}
share|improve this question
    
Welcome to Code Review! If you're not sure if it's working, this could potentially be off-topic! Take the time, make some tests and verify that everything works. –  Marc-Andre Apr 28 at 12:05

1 Answer 1

up vote 0 down vote accepted
   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;
            }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.