public boolean insert(K key, V value) {
    if (contains(key)) { //if the binary tree contains it don't insert it.
        return false;
    }
    if (rNode == null) { //if the root node is empty, there is nothing in the tree
        //create a new DictionaryNode.
        rNode = new DictionaryNode<K, V>(key, value);
        curNode = rNode;
    } else {//if the above aren't true then you can insert it.
        placeNode(key, value, rNode, null, false); //use private method placeNode
    }
    changeCounter++;
    currentSize++;
    return true;
}//end insert


这是另一个功能。我希望能够在我的insert方法中执行placeNode的所有操作。我希望能够摆脱我的placeNode方法。

private void placeNode(K key, V value, DictionaryNode<K, V> node, DictionaryNode<K, V> parent, boolean nodeLeft) {
    if (node == null) {
        if (nodeLeft) {
            parent.lChild = new DictionaryNode<K, V>(key, value);
        } else {
            parent.rChild = new DictionaryNode<K, V>(key, value);
        }
    } else if (((Comparable<K>) key).compareTo(node.key) < 0) {
        placeNode(key, value, node.lChild, node, true);
    } else {
        placeNode(key, value, node.rChild, node, false);
    }
}//end placeNode

最佳答案

private DictionaryNode<K, V> curNode = rNode;
public boolean insert(K key, V value) {
            if (contains(key)) { // if the binary tree contains it don't insert it.
                return false;
            }
            if (rNode == null) { // if the root node is empty, there is nothing in
                                    // the tree
                                    // create a new DictionaryNode.
                rNode = new DictionaryNode<K, V>(key, value);

            } else {// if the above aren't true then you can insert it.

                int c = ((Comparable<K>)key).compareTo(curNode.key);


                if (c < 0) {
                    if (curNode.lChild == null) {
                        curNode.lChild = new DictionaryNode<K, V>(key, value);
                    }
                    else {
                        curNode = curNode.lChild;
                        return insert(key, value);
                    }
                }
                else {
                    if (curNode.rChild == null) {
                        curNode.rChild = new DictionaryNode<K, V>(key, value);
                    }
                    else {
                        curNode = curNode.rChild;
                        return insert(key, value);
                    }
                }

            }
            curNode = rNode;
            changeCounter++;
            currentSize++;
            return true;
        }


编辑-

假设K和V来自类声明,则应将它们声明为

public SomeClass<K extends Comparable<K>, V extends Comparable<V> { ... }


如诚所建议。

07-26 04:08