-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.py
44 lines (37 loc) · 1.28 KB
/
Solution.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
41
42
43
44
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getDirections(
self, root: Optional[TreeNode], startValue: int, destValue: int
) -> str:
def lca(node: Optional[TreeNode], p: int, q: int):
if node is None or node.val in (p, q):
return node
left = lca(node.left, p, q)
right = lca(node.right, p, q)
if left and right:
return node
return left or right
def dfs(node: Optional[TreeNode], x: int, path: List[str]):
if node is None:
return False
if node.val == x:
return True
path.append("L")
if dfs(node.left, x, path):
return True
path[-1] = "R"
if dfs(node.right, x, path):
return True
path.pop()
return False
node = lca(root, startValue, destValue)
path_to_start = []
path_to_dest = []
dfs(node, startValue, path_to_start)
dfs(node, destValue, path_to_dest)
return "U" * len(path_to_start) + "".join(path_to_dest)