-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aug-20-14.py
37 lines (35 loc) · 1.15 KB
/
Aug-20-14.py
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
from collections import defaultdict
class Solution:
def minTime(self, root,target):
return self.burn_tree(root,target)
def build_map(self,node, parent, graph):
if node is None:
return
if node not in graph:
graph[node.data] = []
if parent is not None:
graph[node.data].append(parent.data)
graph[parent.data].append(node.data)
self.build_map(node.left, node, graph)
self.build_map(node.right, node, graph)
def burn_tree(self,root, target):
graph = defaultdict(list)
self.build_map(root, None, graph)
if target not in graph:
return 0
visited = set()
queue = []
queue.append(target)
visited.add(target)
cnt = 0
while queue:
size = len(queue)
for i in range(size):
node = queue.pop(0)
for next in graph[node]:
if next in visited:
continue
visited.add(next)
queue.append(next)
cnt += 1
return cnt-1