Approach
Breadth-first search
For Tree Diameter, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 136 lines of Python from the credited upstream file tree-diameter.py.
- The implementation visibly relies on sequence storage, ordered lookup, cached states.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def treeDiameter(self, edges):7 """8 :type edges: List[List[int]]9 :rtype: int10 """11 def iter_dfs():12 result = 013 stk = [(1, (0, -1, [0]))]14 while stk:15 step, args = stk.pop()16 if step == 1:17 u, p, ret = args18 for v in reversed(adj[u]):19 if v == p:20 continue21 ret2 = [0]22 stk.append((2, (ret2, ret)))23 stk.append((1, (v, u, ret2)))24 elif step == 2:25 ret2, ret = args26 result = max(result, ret[0]+(ret2[0]+1))27 ret[0] = max(ret[0], ret2[0]+1)28 return result29 30 adj = [[] for _ in range(len(edges)+1)]31 for u, v in edges:32 adj[u].append(v)33 adj[v].append(u)34 return iter_dfs()35 36 37383940class Solution2(object):41 def treeDiameter(self, edges):42 """43 :type edges: List[List[int]]44 :rtype: int45 """46 def dfs(u, p):47 mx = 048 for v in adj[u]:49 if v == p:50 continue51 curr = dfs(v, u)52 result[0] = max(result[0], mx+(curr+1))53 mx = max(mx, curr+1)54 return mx55 56 adj = [[] for _ in range(len(edges)+1)]57 for u, v in edges:58 adj[u].append(v)59 adj[v].append(u)60 result = [0]61 dfs(0, -1)62 return result[0]63 64 65666768class Solution3(object):69 def treeDiameter(self, edges):70 """71 :type edges: List[List[int]]72 :rtype: int73 """74 def bfs():75 result = 076 dp = [0]*len(adj)77 degree = map(len, adj)78 q = [u for u in xrange(len(degree)) if degree[u] == 1]79 while q:80 new_q = []81 for u in q:82 if degree[u] == 0:83 continue84 degree[u] -= 185 for v in adj[u]:86 if degree[v] == 0:87 continue88 result = max(result, dp[v]+(dp[u]+1))89 dp[v] = max(dp[v], (dp[u]+1))90 degree[v] -= 191 if degree[v] == 1:92 new_q.append(v)93 q = new_q94 return result95 96 adj = [[] for _ in range(len(edges)+1)]97 for u, v in edges:98 adj[u].append(v)99 adj[v].append(u)100 return bfs()101 102 103104105106class Solution4(object):107 def treeDiameter(self, edges):108 """109 :type edges: List[List[int]]110 :rtype: int111 """112 def bfs(root):113 d = new_root = -1114 lookup = [False]*len(adj)115 lookup[root] = True116 q = [root]117 while q:118 d, new_root = d+1, q[0]119 new_q = []120 for u in q:121 for v in adj[u]:122 if lookup[v]:123 continue124 lookup[v] = True125 new_q.append(v)126 q = new_q127 return d, new_root128 129 adj = [[] for _ in range(len(edges)+1)]130 for u, v in edges:131 adj[u].append(v)132 adj[v].append(u)133 _, root = bfs(0)134 d, _ = bfs(root)135 return d136