Suppose we have an edge list where each items are holding (u, v) represents u is parent of v. We have to find the length of the longest path in the tree. The path length is 1 + number of nodes in that path.
So, if the input is like
then the output will be 5, because the path is [1, 4, 5, 7], there are 4 nodes in total, so path length is 1 + 4 = 5.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(edges): g = {} for u, v in edges: if u not in g: g[u] = [] g[u] += (v,) if v not in g: g[v] = [] g[v] += (u,) d = {} def bfs(o): d[o] = 1 f = o q = [o] for x in q: for y in g[x]: if y not in d: d[y] = d[x] + 1 if d[y] > d[f]: f = y q += (y,) return f for o in g: f = bfs(o) d = {} return d[bfs(f)] return 0 edges = [(1, 2),(1, 3),(1, 4),(4, 5),(5,7),(1,6),(4,8)] print(solve(edges))
[(1, 2),(1, 3),(1, 4),(4, 5),(5,7),(1,6),(4,8)]
5