查找从一个节点到另一个节点的级别数

时间:2011-03-27 05:14:50

标签: c++ tree

我正在尝试编写一个函数,它将在四叉树中将一个节点的级别数返回到另一个节点。

这是我到目前为止所做的,但我确定这是不正确的,我只是想弄清楚原因:

int levels(QtreeNode * orig, QtreeNode * n) {

    //calculates the number of levels from orig to n
    if(orig==n)
        return 0;
    if(!orig->isLeaf())
        return 1 + levels(orig->nwChild, n) + levels(orig->neChild, n) + levels(orig->swChild, n)+ levels(orig->seChild, n);
    return 0;   

}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你的错误是你在死路径的路径上添加了级别,但是你需要将这两个节点的方法联系起来

int levels(QtreeNode * orig, QtreeNode * n)
{
    int path;

    // found!
    if (orig == n)
        return 0;
    // it's dead end, do not calc that way
    if (orig->isLeaf())
        return -1;
    path = levels(orig->nwChild, n);
    // not dead end? it's fine, return that path
    if (path >= 0)
        return 1 + path;
    path = levels(orig->neChild, n);
    // not dead end? it's fine, return that path
    if (path >= 0)
        return 1 + path;
    path = levels(orig->swChild, n);
    // not dead end? it's fine, return that path
    if (path >= 0)
        return 1 + path;
    path = levels(orig->seChild, n);
    // not dead end? it's fine, return that path
    if (path >= 0)
        return 1 + path;
    // there is no path between this nodes
    return -2;
}
相关问题