-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0863-all-nodes-distance-k-in-binary-tree.py
More file actions
57 lines (46 loc) · 1.5 KB
/
0863-all-nodes-distance-k-in-binary-tree.py
File metadata and controls
57 lines (46 loc) · 1.5 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
# time complexity: O(n)
# space complexity: O(n)
from collections import defaultdict, deque
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
graph = defaultdict(list)
def buildGraph(curr: TreeNode, parent: TreeNode):
if curr and parent:
graph[curr.val].append(parent.val)
graph[parent.val].append(curr.val)
if curr.left:
buildGraph(curr.left, curr)
if curr.right:
buildGraph(curr.right, curr)
buildGraph(root, None)
queue = deque()
queue.append((target.val, 0))
seen = set([target.val])
result = []
while queue:
currNodeVal, distance = queue.popleft()
if distance == k:
result.append(currNodeVal)
for neighbor in graph[currNodeVal]:
if neighbor not in seen:
queue.append((neighbor, distance + 1))
seen.add(neighbor)
return result
root = TreeNode(3)
root.left = TreeNode(5)
root.right = TreeNode(1)
root.left.left = TreeNode(6)
root.left.right = TreeNode(2)
root.right.left = TreeNode(0)
root.right.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(4)
target = TreeNode(5)
k = 2
print(Solution().distanceK(root, target, k))