1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
class Solution:
class TreeNode:
def __init__(self, val: str):
self.val: str = val
self.children: List['Solution.Edge'] = []
class Edge:
def __init__(self, node: 'Solution.TreeNode', weight: int):
self.node: 'Solution.TreeNode' = node
self.weight: int = weight
def __init__(self):
self.max_len = 0
def longestPath(self, nodes: List[str], edges: List[Tuple[str, str, int]]) -> int:
node_map: Dict[str, 'Solution.TreeNode'] = {val: self.TreeNode(val) for val in nodes}
for parent, child, weight in edges:
node_map[parent].children.append(self.Edge(node_map[child], weight))
if not nodes:
return 0
self.dfs(node_map[nodes[0]])
return self.max_len
def dfs(self, node: 'Solution.TreeNode') -> int:
if not node:
return 0
max1, max2 = 0, 0
for edge in node.children:
length = self.dfs(edge.node) + edge.weight
if length > max1:
max2 = max1
max1 = length
elif length > max2:
max2 = length
self.max_len = max(self.max_len, max1 + max2)
return max1
# Example usage:
nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
edges = [('a', 'b', 3), ('a', 'c', 5), ('a', 'd', 8), ('d', 'e', 2), ('d', 'f', 4), ('e', 'g', 1), ('e', 'h', 1)]
sol = Solution()
print(sol.longestPath(nodes, edges)) # Output: 17
|