简体   繁体   中英

How do you handle duplicates in binary tree?

This is the testing part of it, I keep getting a return of 2 instead of fff. I need to have implemented on the bottom to return the duplicates. ?Handling duplicates but not trying to prevent them from inserting it, just have to return correct value.

        System.out.println("\nInsering duplicate key: ...");
        tree.insert(2, "fff");
        testFind(tree.find(2), 2, "fff");

I need to handle duplicates and return "fff" above ^ is the test code bottom needs to be further implemented.

    public V find(K key) {
        Node node = findHelper(key, root);
        if (node == null) {
            return null;
        } else {
            return (V) node.entry.value;
        }
    }


    public Node findHelper(K key, Node node) {
        if (node.entry.key.compareTo(key) == 0) {
            return node;
        }
        else if (node.entry.key.compareTo(key) > 0) {
            if (node.leftChild == null) {
                return null;
            } else {
                return findHelper(key, node.leftChild);
            }
        } else if (node.entry.key.compareTo(key) < 0) {
            if (node.rightChild == null) {
                return null;
            } else {
                return findHelper(key, node.rightChild);
            }
        }
        return node;
    }

If a node entry key equals to query, you should continue searching in child nodes too:

public List<Node> findHelper(K key, Node node) {

    int c = node.entry.key.compareTo(key);

    if (c == 0) {
         List<Node> result = new ArrayList<>();
         result.add(node);
         result.addAll(findHelper(key, node.leftChild));
         result.addAll(findHelper(key, node.rightChild));
         return result;        

    } else if (c > 0) {
        if (node.leftChild == null) 
            return Collections.emptyList();
        else 
            return findHelper(key, node.leftChild);

    } else {
        if (node.rightChild == null) 
            return Collections.emptyList();
        else 
            return findHelper(key, node.rightChild);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM