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

This is my implementation based on Map<K,V> interface. The BST is a linked binary tree with root reference, both internal and external nodes (MyBSNode) contains (key, value) entries

What do you think? There's something to improve?

public BSPosition<E> insert(int k, E e) {
    if(isEmpty()){
        /* Sets root */
        BSPosition<E> r = new MyBSNode<E>(null);
        r.setElement(k, e);
        setRoot(r);
        size++;
        return r;
    }

    BSPosition<E> n = treeInsert(k, root);          //k-key node or last node visited
    if(k == n.getKey()){                            //tree has already a k-key node
        n.setElement(k, e);                         //only modifies e
        return n;           
    }
    /* n is a external (last visited) node with different key */
    size++;
    if(k < n.getKey())
        return n.setLeftChild(k, e);
    else 
        return n.setRightChild(k, e);

}

private BSPosition<E> treeInsert(int k, BSPosition<E> v){
    if(isLeaf(v))                       return v;           

    if(k < v.getKey()){
        if(v.getLeftChild() == null)    return v;
        return treeInsert(k, v.getLeftChild());
    }
    else if(k == v.getKey())            return v;

    else{
        if(v.getRightChild() == null)   return v;
        return treeInsert(k, v.getRightChild());
    }
}
share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.