i got it success but error and i cant find it

my code here:

bool BinarySearchTree::search(int d)
{
    tree_node *t = head;
    if(root==NULL)

        cout<<" The Tree is empty. Please insert a value "<<endl;


    while (t != NULL)
    {

        if (t->data == d)
            break;

        else if (d > t->data)
            t = t->right;
        else                  
        //(d < t->data)
            t = t->left;
    }

    if (t == NULL)
        return false;

    if (t->data == d)
    cout << "found" <<endl;
        return true;

    return false;
}

Is there an error message? Does it compile? Does it crash? Does it not do what you think it does?

Comments
no error but cant search for it. it crash

no error but cant search for it. it crash

Run it under a debugger. Then you will know which line it crashes on, and you can check the values of the variables to see what the problem is.

Comments
how to run it. i was run it with "start without debugging"

It may help to show your list structures as well. Also, this is very clumsy code and prone to logic errors. In addition, your lack of appropriate scoping (bracing) of your logic means that the return values are not what you think. Example, this code:

if (t->data == d)
    cout << "found" <<endl;
return true;

Will ALWAYS return true, even if it isn't. This is how it should be scoped:

if (t->data == d)
{
    cout << "found" <<endl;
    return true;
}

Edited 1 Year Ago by rubberman

To me, line 25 until the end could be replaced with return true; because if and only if t->data is equal to d would get to that point (or the value would be null).

I believe the problem with the OP could be from inserting a node to the tree. The search looks fine to me...

This article has been dead for over six months. Start a new discussion instead.