0

我目前正在研究一个具有 1 个辅助函数的函数,主函数接收 2 个字符串并搜索第一个字符串(它成为一个引用,就像它是 m_root)和第二个要在树中搜索的字符串。一旦他们被搜索到,我的助手功能应该搜索第二个城市并计算它必须行驶的距离,就好像一辆卡车开往那个城市一样。

    int Stree::distance(string origin_city, string destination_city)
{
    int total_distance = 0;
    Node *new_root = m_root;
    new_root = find_node(m_root, origin_city);
    total_distance = get_distance(new_root, total_distance, destination_city);
    return total_distance;
}

int Stree::get_distance(Node* cur, int distance, string destination)
{
    Node *tmp = cur;
    if(cur == NULL)
        return 0;
    if(cur->m_city == destination || tmp->m_city == destination)
    {
        //cout << distance + cur->m_parent_distance << endl;
        return distance += cur->m_parent_distance;
    }
    if(tmp->m_left != NULL)
    {
        //cout << "checking left" << endl;
        tmp = cur->m_left;
        return get_distance(cur->m_left, distance, destination) ;
    }
    else
    {
        //cout << "checking right" << endl;
        return get_distance(cur->m_right, distance, destination);
    }
}
4

1 回答 1

0

粗略一瞥,我看不到您修改或增加距离的任何地方,无论是距离变量还是类似的东西:

    return 1 + get_distance(cur->m_right, distance, destination);

所以我会确保在算法意义上,每一步都被计算在内,否则每次肯定会返回 0。

于 2013-05-18T05:34:30.407 回答