Brandon Bosso
Brandon Bosso

Reputation: 157

searching for a value in a binary search tree

I am working on a function that searches a templated binary search tree for a value with a given key and then returns a pointer to that data value. If the given key doesn't exist in the tree, the pointer it returns should point to NULL. So far I have:

template <typename Item, typename Key>
Item* BSTree<Item,Key>::search(const Key& key) const {
    Item* entry = NULL;
    Node* cursor = root;
    while(cursor != NULL) {
        if(key > cursor->data) 
            cursor = cursor->right;
        else if(key < cursor->data)
            cursor = cursor->left;
        else
            entry = cursor->data;
    }
    return entry;
}

But I get errors when I try and run it that say I can't convert from Item to Item*. I've always had trouble with pointers and can't figure out a way to fix these errors.

Upvotes: 0

Views: 192

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490098

Instead of entry = cursor->data; you apparently need entry = &(cursor->data);.

Also note that once you find your item, you probably want to return it immediately, not continue traversing the tree looking at more items.

Upvotes: 1

Related Questions