Skip to content

Commit b8fe657

Browse files
committed
Sync LeetCode submission Runtime - 46 ms (25.23%), Memory - 18 MB (61.26%)
1 parent 98f2d22 commit b8fe657

File tree

1 file changed

+25
-17
lines changed

1 file changed

+25
-17
lines changed
Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
# Approach 1: Implementing Parent Pointers
1+
# Approach 2: Depth-First Search on Equivalent Graph
22

33
# Time: O(n)
44
# Space: O(n)
55

6+
from collections import defaultdict
7+
68
# Definition for a binary tree node.
79
# class TreeNode:
810
# def __init__(self, x):
@@ -12,27 +14,33 @@
1214

1315
class Solution:
1416
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
15-
def add_parent(curr, parent):
16-
if curr:
17-
curr.parent = parent
18-
add_parent(curr.left, curr)
19-
add_parent(curr.right, curr)
20-
add_parent(root, None)
17+
graph = defaultdict(list)
18+
19+
# Recursively build the undirected graph from the given binary tree
20+
def build_graph(curr, parent):
21+
if curr and parent:
22+
graph[curr.val].append(parent.val)
23+
graph[parent.val].append(curr.val)
24+
if curr.left:
25+
build_graph(curr.left, curr)
26+
if curr.right:
27+
build_graph(curr.right, curr)
28+
29+
build_graph(root, None)
2130

2231
answer = []
23-
visited = set()
32+
visited = set([target.val])
2433

2534
def dfs(curr, distance):
26-
if not curr or curr in visited:
27-
return
28-
visited.add(curr)
29-
if distance == 0:
30-
answer.append(curr.val)
35+
if distance == k:
36+
answer.append(curr)
3137
return
32-
dfs(curr.parent, distance - 1)
33-
dfs(curr.left, distance - 1)
34-
dfs(curr.right, distance - 1)
38+
for neighbor in graph[curr]:
39+
if neighbor not in visited:
40+
visited.add(neighbor)
41+
dfs(neighbor, distance + 1)
3542

36-
dfs(target, k)
43+
dfs(target.val, 0)
3744

3845
return answer
46+

0 commit comments

Comments
 (0)