一开始没看提示,没想LCA,先写了DFS的版本。结果第287个TC会TLE。建立一个parent的dic,用于往外dfs的时候找node的父节点。
# 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:
self.parent = collections.defaultdict(TreeNode)
self.dic = collections.defaultdict(TreeNode)
que = collections.deque()
que.append(root)
que2 = collections.deque()
while que:
curnode = que.popleft()
if curnode.val == startValue:
que2.append(curnode)
if curnode.val == destValue:
que2.append(curnode)
if len(que2) == 2:
break
if curnode.left:
self.parent[curnode.left] = curnode
que.append(curnode.left)
if curnode.right:
self.parent[curnode.right] = curnode
que.append(curnode.right)
for node in que2:
if node.val == startValue:
startnode = node
def dfs(node, res, destValue, meet, dic):
if node.val in meet:return #题目说node val是唯一的
meet.add(node.val)
if node.val == destValue:
dic[destValue] = res
return
else:
if node.left:
dfs(node.left, res+'L', destValue, meet, dic)
if node.right:
dfs(node.right, res+'R', destValue, meet, dic)
if self.parent[node]:
dfs(self.parent[node], res+'U', destValue, meet, dic)
dfs(startnode, '', destValue, set(), self.dic)
return self.dic[destValue]
接下来写LCA版本的。找到LCA,LCA往左的全部改成“U”,右边的保持不变就好。作者自己注意:下次一定把LCA这个写法当作模版背下来。
# 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:
lcanode = self.lca(root, startValue, destValue)
que = collections.deque()
res = ''
startpath = ''
destpath = ''
que.append((lcanode, res))
# print(que)
while que:
curnode, curpath = que.popleft()
if curnode.val == startValue:
startpath = curpath
if destpath:break
elif curnode.val == destValue:
destpath = curpath
if startpath:break
if curnode.left:
que.append((curnode.left, curpath + 'L'))
if curnode.right:
que.append((curnode.right, curpath + 'R'))
for _ in range(len(startpath)):
res += 'U'
for char in destpath:
res += char
return res
def lca(self,node, left, right):
if not node:return None
if node.val in [ left, right]:
return node
leftpath = self.lca(node.left, left, right)
rightpath = self.lca(node.right, left, right)
if leftpath is None:
return rightpath
if rightpath is None:
return leftpath
return node