tags:

views:

113

answers:

3

Well I'm down to the last function of my program and I'm done. I've hit another stump that I can't seem to fix on my own.

int Tree::InternalPathLength(Node * r, int value)
{
    if(r->left == NULL && r->right == NULL)
    {
        return 0;
    }
    return value + InternalPathLength(r->left, value+1) + 
        InternalPathLength(r->right, value+1);
 }

I feel like i'm close to the solution, but i know i'm missing something. I think it's another if statement and i've tried different combinations but i end up getting a crashed program or 0 for the answer.

Any suggestions or help would be much appreciated ! thanks!

+1  A: 

May be this works:

int Tree::InternalPathLength(Node * r, int value)
{
    if(r->left == NULL && r->right == NULL)
    {
        return 0;
    }
    return value + ( r->left? InternalPathLength(r->left, value+1):0 )
                 + ( r->right? InternalPathLength(r->right, value+1):0 );
 }

or just add NULL check for NODE

int Tree::InternalPathLength(Node * r, int value)
{
    if (r == NULL ) return 0;
    if(r->left == NULL && r->right == NULL)
    {
        return value +1;
    }
    return value + InternalPathLength(r->left, value+1) + 
        InternalPathLength(r->right, value+1);
 }
pinichi
should it be `value + max(r->left ? InternalPathLength(r->left) : 0, r->right ? InternalPathLength(r->right) : 0)` ?
rwong
Yes, I didn't noticed Internal Path Length, then must be modified.
pinichi
I've just tried your most recently updated suggested, well my program doesn't crash anymore, but it just returns 0 as the Internal Path Length.
MOneAtt
Fixed your `r = NULL` problem.
Blindy
@Blindy:Thank you. @MOneAtt: Check the last once more time.
pinichi
Okay found out why it was returning 0 every time, a mistake on my part. that's fixed now. Your first code pops out with 0 and 6. the second code crashes. The correct answer is 2 and 19. So still not working for me. Sorry, but thanks for the effort
MOneAtt
A: 

maybe you can pass in the value counter as reference? then increment it every time the function is called ? idk .. i am working on a program due tomorrow as well that needs this same function...

Daniel Britt
see my answer i just posted
MOneAtt
Well it seems like we should stop posting actual answers until tomorrow.
rwong
A: 
if(r == NULL) 
{
    return 0;
}
return (value+InternalPathLength(r->right,value+1)+InternalPathLength(r->left,value+1));

I finally got it!

Thanks for your help though!

MOneAtt
Perfect! When both left and right = NULL (leef), not 0 but value+1 should be returned.
pinichi