Ronzii's Blog

Just your average geek's blog

Given a binary tree, return the length of the longest path. Length is defined as number of nodes in the path

struct node
{
    struct node* left;
    struct node* right;
    int data;
};
typedef struct node TreeNode;
int longestPath(TreeNode* current, int *height)
{
    if(current==NULL)
    {
        *height = 0;
        return 0;
    }
    else
    {
        int lh=0,rh=0;
        int lp_left =  longestPath(current->left, &lh);
        int lp_right = longestPath(current->right, &rh);
        *height = lh+rh+1;
        return max(*height,max(lp_left,lp_right));
    }
}
Advertisements

March 8, 2012 - Posted by | C++ | , , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s