Skip to content

Commit 1d12169

Browse files
authored
Update Solution.py
1 parent ac1daa4 commit 1d12169

File tree

1 file changed

+31
-30
lines changed
  • solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another

1 file changed

+31
-30
lines changed

solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/Solution.py

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,41 @@
44
# self.val = val
55
# self.left = left
66
# self.right = right
7+
8+
79
class Solution:
810
def getDirections(
911
self, root: Optional[TreeNode], startValue: int, destValue: int
1012
) -> str:
11-
edges = defaultdict(list)
12-
ans = None
13-
visited = set()
13+
def lca(node: Optional[TreeNode], p: int, q: int):
14+
if node is None or node.val in (p, q):
15+
return node
16+
left = lca(node.left, p, q)
17+
right = lca(node.right, p, q)
18+
if left and right:
19+
return node
20+
return left or right
21+
22+
def dfs(node: Optional[TreeNode], x: int, path: List[str]):
23+
if node is None:
24+
return False
25+
if node.val == x:
26+
return True
27+
path.append("L")
28+
if dfs(node.left, x, path):
29+
return True
30+
path[-1] = "R"
31+
if dfs(node.right, x, path):
32+
return True
33+
path.pop()
34+
return False
35+
36+
node = lca(root, startValue, destValue)
1437

15-
def traverse(root):
16-
if not root:
17-
return
18-
if root.left:
19-
edges[root.val].append([root.left.val, 'L'])
20-
edges[root.left.val].append([root.val, 'U'])
21-
if root.right:
22-
edges[root.val].append([root.right.val, 'R'])
23-
edges[root.right.val].append([root.val, 'U'])
24-
traverse(root.left)
25-
traverse(root.right)
38+
path_to_start = []
39+
path_to_dest = []
2640

27-
def dfs(start, dest, t):
28-
nonlocal ans
29-
if start in visited:
30-
return
31-
if start == dest:
32-
if ans is None or len(ans) > len(t):
33-
ans = ''.join(t)
34-
return
35-
visited.add(start)
36-
for d, k in edges[start]:
37-
t.append(k)
38-
dfs(d, dest, t)
39-
t.pop()
41+
dfs(node, startValue, path_to_start)
42+
dfs(node, destValue, path_to_dest)
4043

41-
traverse(root)
42-
dfs(startValue, destValue, [])
43-
return ans
44+
return "U" * len(path_to_start) + "".join(path_to_dest)

0 commit comments

Comments
 (0)