如何总结树结构中从child开始到根的child值?

How to sum up the child values that starts from child to root in a tree structure?

我想获取每个节点的绝对值。绝对值表示距离根的距离。

如果我有骨架模型。

根child是

root
left hip - child
left knee - child
left foot - child

assume that all the bones lengths are equal to 1.
root to hip = 1
hip to knee = 1
knee to foot = 1

所以如果我想从根部得到脚关节的位置,应该是3。对吗?

root to foot = root to hip + hip to knee + knee to foot = 3

所以这些是我正在使用的子程序..

void ComputeAbs()
{
    for(unsigned int i=1; i<nNodes(); i++) 
    {
        node* b = getNode(i);
        if(b)
        {
            b->nb = ComputeAbsSum(b);
        }
    }
}

int ComputeAbsSum(node *b)
{
    int m = b->nb;
    if (b->child != NULL) 
    {
        m *= ComputeAbsSum(b->child);
    }
    return m;
}

输出会像

root to hip = 3
root to knee = 2
root to foot = 1

But I want in a reverse way, i should get like this

root to hip = 1
root to knee = 2
root to foot = 3

我怎样才能达到这个结果?如何添加树 child 的值从 child 开始到根?

最后objective是通过计算一个关节的绝对变换得到最终的pose

bonePoseAbsolute[i] = bonePoseAbsolute[parentIndex] * bonePoseRelative[i];

谢谢。

看起来你的递归有问题。尝试

int ComputeAbsSum(node *b)
{
    int result = 1;
    if (b->child != NULL)
        result += ComputeAbsSum(b->child);
    return result;
}

*编辑:如果要反向遍历树,

int ComputeAbsSumReverse(node *b)
{
    int result = 1;
    if (b->parent != NULL)
        result += ComputeAbsSum(b->parent);
    return result;
}