2

I'm trying to make a binary tree that does not accept duplicates ironically I've been able to do the opposite:

public void insertLeaf(String a){
    Node newNode = new Node(a);
    if(node==null){
        node=newNode;
        return;
    }
    Node currentValue = node;
    Node parent = null;
    while(true){
        parent = currentValue;
        if(a.compareTo(currentValue.data)<0){               
            currentValue = currentValue.left;

            if(currentValue==null ){
                parent.left = newNode;
                return;
            }
        }else{
            currentValue = currentValue.right;
            if(currentValue==null){
                parent.right = newNode;
                return;
            }
        }   
    }
}

Heres the Node class

class Node{
    String data;
    Node left;
    Node right; 
    public Node(String data){
        this.data = data;
        left = null;
        right = null;
    }
}

Thanks for your help.

2

1 Answer 1

2

The problem is your else clause - it accepts both the cases of a.compareTo(currentValue.data)>0 and a.compareTo(currentValue.data)==0. It should only accept the former. When a.compareTo(currentValue.data)==0, you shouldn't add the value to the tree.

Your condition should be :

    if(a.compareTo(currentValue.data)<0){               
        currentValue = currentValue.left;
        if(currentValue==null ){
            parent.left = newNode;
            return;
        }
    } else if (a.compareTo(currentValue.data)>0) {
        currentValue = currentValue.right;
        if(currentValue==null){
            parent.right = newNode;
            return;
        }
    } else {
        return; // don't add the a duplicate value
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.