Function not returning what I need it to

So the function is working. I'm trying to search for a Node of zip codes in a binary tree created from a file. and it finds it. However, when I try to return the value back to the main function it doesn't work properly.I think it has to do with passing the Node between functions,but I don't see what is wrong.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

//In BinarySearchTree.cpp
template <class T>
T BST<T>::GetItem(T item, bool& found)
{
     return Retrieve(root,item,found); //tried to cout the Node here 
     //and it wouldn't
}

template <class T>
T BST<T>::Retrieve(NodePointer temp, T item, bool& found) 
{
     if(temp==NULL)
     found=false;
     else if(item< temp->data)
     Retrieve(temp->left,item,found);
     else if (item > temp->data)
     Retrieve(temp->right,item,found);
    else
    {

     item = temp->data;
     found = true;
     return temp->data;//cout'ed this in this function and it worked fine(I overloaded the operator). This is where the Node is found at.
}
}

//In main.cpp
bool found=false;
cout<<"Enter zip: ";
cin>>zip;

search.setZip(zip);//assign a zip
Zipfile zipfile1 = zipfile.GetItem(search,found);//this operator is overloaded too but its just crashing. 
Last edited on
your problem is this:
1
2
3
4
     if(temp==NULL)
     found=false; // you set found, but you never check it + the return value is undefined
     else if(item< temp->data)
     Retrieve(temp->left,item,found); // what happens to the return value here? 


so your problem is the return value. found is for the recursion irrelevant.

you can solve it like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <class T>
T BST<T>::Retrieve(NodePointer temp, T item, bool& found) 
{
     T result = T(); // this sets the return value to default

     if(temp==NULL)
     found=false;
     else if(item< temp->data)
     result = Retrieve(temp->left,item,found);
     else if (item > temp->data)
     result = Retrieve(temp->right,item,found);
    else
    {

     item = temp->data;
     found = true;
     result = temp->data;//cout'ed this in this function and it worked fine(I overloaded the operator). This is where the Node is found at.
}
     return result;
}
Topic archived. No new replies allowed.