1

i am trying to learn tree with C. i need to find longest path. i am using recursive approach for this. but i am getting segmentation fault. i am not able to find why it is happening. i dont need logic. i want to do it on my own. just want to know what basic fault I am doing.

Any suggestion for handling pointers is most welcome.

void longestPath(struct node *p,int *maxlen,int count)
{
    if(p==NULL)
        return;

    count++;

    if(p->lft==NULL && p->rt==NULL )
    {
        if(*maxlen<count)
             *maxlen=count;
    }

    longestPath(p->lft,maxlen,count);
    longestPath(p->rt,maxlen,count); 
} 
5
  • You want || instead of &&. Commented Jan 1, 2014 at 16:40
  • 2
    Shouldn't p->lft==NULL && p->rt==NULL be p->lft==NULL || p->rt==NULL? Commented Jan 1, 2014 at 16:40
  • 2
    Run in a debugger. It might be that you don't set the leaf nodes left or right pointers to NULL. Commented Jan 1, 2014 at 16:41
  • 1
    Looks like your tree itself is broken. Commented Jan 1, 2014 at 16:46
  • I agree with @self. I can't see any wrong thing in your function. Provided that it is called with a valid tree and valid pointer for maxlen, this should work. I also think that it's not || but && as you have put it, because you want to detect when you have come to the end of a branch. Commented Jan 1, 2014 at 16:49

2 Answers 2

2

Check maxlen for NULL also. That is likely the problem you are dereferecing the pointer without validating it.

int maxpath = 0;
int count = 10; // for example
struct node* nodes; // initialized somewhere else
longestPath( nodes, &maxpath, count );
Sign up to request clarification or add additional context in comments.

2 Comments

thanks TimDave. it was same you said. was not using malloc. sometimes it works without malloc also. do you have any idea why. should i be always passing pointer only after malloc?
You can declare the variable on the stack and pass its address instead of using malloc. See edited post for example.
1

Instead of passing the result via a pointer, you could use the return value:

unsigned longestPath(struct node *p)
{
    unsigned ll,rr;

    if (!p) return 0;

    ll = longestPath(p->lft);
    rr = longestPath(p->rt);

    return ll > rr ? 1+ll : 1+rr;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.