blob: 0feaae2ef98b96e76a49e80d6c12bb26de606824 (
plain) (
blame)
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
|
#!/usr/bin/env python
import typing
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.right = right
self.left = left
class Solution:
def amountOfTime(self, root: typing.Optional[TreeNode], start: int) -> int:
def dfs(node):
if node is None:
return
if node.left:
graph[node.val].append(node.left.val)
graph[node.left.val].append(node.val)
if node.right:
graph[node.val].append(node.right.val)
graph[node.right.val].append(node.val)
dfs(node.left)
dfs(node.right)
graph = defaultdict(list)
dfs(root)
visited = set()
queue = deque([start])
time = -1
while queue:
time += 1
for _ in range(len(queue)):
current_node = queue.popleft()
visited.add(current_node)
for neighbor in graph[current_node]:
if neighbor not in visited:
queue.append(neighbor)
return time
def main() -> None:
pass
if __name__ == "__main__":
main()
|