c++algorithmvisual-c++treeskeleton-code

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


I want to get the absolute values of each node. Absolute value meaning that the distance from the root.

if I have a skeleton model.

the root childs are

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

So if I want to get the position of foot joint from the root, it should be 3. am I right?

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

so these are the subroutines I am using..

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;
}

the output would be like

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

How can I achieve this result? how to add tree childs values starts from child to root?

the final objective is to get the final pose by calculating the absolute transformation of a joint.

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

Thanks.


Solution

  • It looks like you have a problem in your recursion. Try

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

    *edit: if you want to traverse the tree in reverse,

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