search in a binary tree

烂漫一生 提交于 2019-12-01 11:05:38

Put an else and your problem will disappear.

Because after temp = temp->right; you must check temp again but in your original code you immediately test temp->data which may not be a valid pointer.

bool tree::search(int num)
{
    node *temp = head;

    while (temp != NULL)
    {
        if (temp->data == num)
            break;

        if (num > temp->data)
            temp = temp->right;
        else                  //  <--- Put this 'else' here
        if (num < temp->data)
            temp = temp->left;
    }

    if (temp == NULL)
        return false;

    if (temp->data == num)
        return true;

    return false;
}

std::set

Use a std::set; it is basically STL's binary tree. If you want to search for something, you would use count, find or lower_bound.

Implementing basic data structures are good exercises, but in production, try to use STL first, as they are implemented by professionals with specific knowledge of the compiler/platform in question. Boost is another great set of data structures and common idioms.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!