题目描述:
方法一:深度优先:
class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: adjacency = collections.defaultdict(set) for i,j in edges: adjacency[i].add(j) adjacency[j].add(i) memo = {} def dfs(i,j): if (i,j) in memo: return memo[i,j] longest = 0 for k in adjacency[j]: if k == i:continue longest = max(longest,dfs(j,k)) memo[(i,j)] = longest + 1 return memo[(i,j)] for i,j in edges: dfs(i,j) dfs(j,i) return max(memo[(i,j)]+memo[(j,i)]-1 for i,j in edges)
方法二:广度优先
class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: adjacency = collections.defaultdict(set) for i,j in edges: adjacency[i].add(j) adjacency[j].add(i) def bfs(node): queue = collections.deque() queue.append((node,0)) memo = {node} while queue: n,long = queue.popleft() for nei in adjacency[n]: if nei not in memo: memo.add(nei) queue.append((nei,long+1)) return n,long far,long = bfs(0) far2,longest = bfs(far) return longest