使用重复键插入二进制搜索树?

时间:2015-11-18 20:46:32

标签: java binary-search-tree

现在,当我将键/值插入BST然后搜索它们时,我得到空值。我想获得一些关于如何处理重复键的帮助。

    private Node put(Node root, final Key key, final Value value) {
    if (root == null)
        return new Node(key, value, 1);

    final int result = key.compareTo(root.key);

    if (result > 0)
        root.right = put(root.right, key, value);
    else if (result <= 0) {
        root.left = put(root.left, key, value);
    }
    root.size = size(root.left) + size(root.right) + 1;
    return root;
}

private Value get(final Node root, final Key key) {
    if (root == null)
        return null;

    final int result = key.compareTo(root.key);

    if (result > 0)
        return get(root.right, key);
    else if (result <= 0)
        return get(root.left, key);
    return root.value;
}

1 个答案:

答案 0 :(得分:0)

Your get code needs an == check. Your <= 0 check is grabbing the node to the left where you want < 0. Your == check should return the root.value.

Something like:

private Value get(final Node root, final Key key) {
    if (root == null)
        return null;

    final int result = key.compareTo(root.key);

    if (result > 0)
        return get(root.right, key);
    else if (result < 0)
        return get(root.left, key);
    else if (result == 0)
        return root.value;
    else
        return null; //key not found
}