-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution2.py
39 lines (35 loc) · 1.16 KB
/
Solution2.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
# 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 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
path_to_start = []
path_to_dest = []
dfs(root, startValue, path_to_start)
dfs(root, destValue, path_to_dest)
i = 0
while (
i < len(path_to_start)
and i < len(path_to_dest)
and path_to_start[i] == path_to_dest[i]
):
i += 1
return "U" * (len(path_to_start) - i) + "".join(path_to_dest[i:])