c ++试图找到2个节点之间的距离

时间:2013-05-18 05:04:48

标签: c++ binary-search-tree

我目前正在处理一个具有1个辅助函数的函数,main函数接受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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

所以我要确保在算法意义上,每走一步都会被计算,否则每次都会返回0.