PT07Z SPOJ : Longest Path in a Tree

Can any one please explain The DFS method of doing this?

Kindly do not give any external reading source links like topcoder or any blog.

Thanks in advance. :smiley:

1 Like

@shivamiet
Apply DFS Two times

1.apply dfs for node 1 and store distance for every node in a array
2.apply dfs for the node with maximum distance

 dist[1]=0;
dfs(1,0);

int node=0;
for(int i=1;i<=n;i++)
{
    if(dist[i]>dist[node])
    {
        node=i;
    }
    
}
memset(vis,0,sizeof(vis));
dfs(node,0);
sort(dist,dist+n+1);
cout<<dist[n];

think of remaining
happy coding :slight_smile:

1 Like