user4607968
user4607968

Reputation:

Using String as BST key in java

I have a binary search tree which stores objects. Can I use String value is a key, It only stores the first key and also searches only the first value, all other keys find returns a null

The first Value is A

this my code: help!

  public void addNode(String key, String name) {
    // Create a new Node and initialize it
    Node newNode = new Node(key, name);
    // If there is no root this becomes root
    if (root == null) {
        root = newNode;
    } else {
        // Set root as the Node we will start
        // with as we traverse the tree
        Node focusNode = root;
        // Future parent for our new Node
        Node parent;
        while (true) {
            parent = focusNode;
            if (key.compareTo(focusNode.name) <= 0) {
                // Switch focus to the left child
                focusNode = focusNode.leftChild;
                // If the left child has no children
                if (focusNode == null) {
                    // then place the new node on the left of it
                    parent.leftChild = newNode;
                    return; // All Done
                }
            } else if(key.compareTo(focusNode.name) >= 0){ // If we get here put the node on the right
                focusNode = focusNode.rightChild;
                // If the right child has no children
                if (focusNode == null) {
                    // then place the new node on the right of it
                    parent.rightChild = newNode;
                    return; // All Done
                }
            }
        }
    }

}

enter image description here

Upvotes: 0

Views: 1127

Answers (1)

PeterG
PeterG

Reputation: 506

From what I see, your problem is that you are comparing keys with values (name in your case). For example, instead of:

 if (key.compareTo(focusNode.name) <= 0) {...

Try:

if (key.compareTo(focusNode.key) <= 0) {...

Also, another problem is that you are never handling the case that the two keys are equal, but instead you proceed to the left child. You probably want to do something else at that point, I'd guess updating the name and returning from the method.

Upvotes: 1

Related Questions