-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.py
More file actions
57 lines (42 loc) · 1.61 KB
/
Copy pathsolution.py
File metadata and controls
57 lines (42 loc) · 1.61 KB
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
50
51
52
53
54
55
56
57
class Solution:
def minTime(self, root, target):
from collections import deque
parent = {}
q = deque([root])
targetNode = None
# Step 1: Build parent mapping
while q:
curr = q.popleft()
if curr.data == target:
targetNode = curr
if curr.left:
parent[curr.left] = curr
q.append(curr.left)
if curr.right:
parent[curr.right] = curr
q.append(curr.right)
# Step 2: BFS burn
visited = set()
q = deque([targetNode])
visited.add(targetNode)
time = 0
while q:
size = len(q)
burned = False
for _ in range(size):
curr = q.popleft()
if curr.left and curr.left not in visited:
burned = True
visited.add(curr.left)
q.append(curr.left)
if curr.right and curr.right not in visited:
burned = True
visited.add(curr.right)
q.append(curr.right)
if curr in parent and parent[curr] not in visited:
burned = True
visited.add(parent[curr])
q.append(parent[curr])
if burned:
time += 1
return time