-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5. NodesAtK.py
40 lines (31 loc) · 1.06 KB
/
5. NodesAtK.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
38
39
40
class Solution:
def distanceK(self, root, target, k: int):
if not root:
return []
hashmap = {}
def setparents(node, parent=None):
if node:
hashmap[node] = parent
setparents(node.left, node)
setparents(node.right, node)
setparents(root)
distance = 0
q = [target]
vis = set()
while q:
if distance == k:
return [node.val for node in q]
next_q = []
for curr in q:
vis.add(curr)
parent = hashmap[curr]
if parent and parent not in vis:
next_q.append(parent)
if curr.left and curr.left not in vis:
next_q.append(curr.left)
if curr.right and curr.right not in vis:
next_q.append(curr.right)
q = next_q
distance += 1
return []
# Link: https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/submissions/1314157760/