二分搜索的查找节点

查看是否包含键key

// 查看二分搜索树中是否存在键key
public boolean contain(Key key) {
    return contain(root, key);
}
// 查看以node为根的二分搜索树中是否包含键值为key的节点, 使用递归算法
private boolean contain(Node node, Key key) {
    if (node == null) {
        return false;
    }
    if (node.key.compareTo(key) == 0) {
        return true;
    } else if (node.key.compareTo(key) > 0) {
        return contain(node.left, key);
    } else {
        return contain(node.right, key);
    }
}

查找某个键

public Value search(Key key) {
    return search(root, key);
}

private Value search(Node node, Key key) {
    if (node.value == null) {
        return null;
    }
    if (node.key.compareTo(key) == 0) {
        return node.value;
    } else if (node.key.compareTo(key) > 0) {
        return search(node.left, key);
    } else {
        return search(node.right, key);
    }
}

results matching ""

    No results matching ""