作者DJYOMIYAHINA (通通打死)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Tue Jul 16 23:39:19 2024
是只有肥肥被這題搞的要死嗎?
吐了==
一次要肥肥寫我不會寫的LCA
還要肥肥處理python DFS字串concate遇到的MLE
我真的不會寫程式:(
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue:
int) -> str:
LCA = None
def findLCA(root) -> bool:
nonlocal LCA
if root is None:
return False
left_contains = findLCA(root.left)
right_contains = findLCA(root.right)
current_is_target = root.val == startValue or root.val == destValue
if current_is_target and (left_contains or right_contains):
LCA = root
return True
if left_contains and right_contains:
LCA = root
return True
return current_is_target or left_contains or right_contains
findLCA(root)
if LCA is None:
return ""
def findPath(root, target, path):
if root is None:
return False
if root.val == target:
return True
path.append("L")
if findPath(root.left, target, path):
return True
path.pop()
path.append("R")
if findPath(root.right, target, path):
return True
path.pop()
return False
start_path = []
dest_path = []
findPath(LCA, startValue, start_path)
findPath(LCA, destValue, dest_path)
return "U" * len(start_path) + "".join(dest_path)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.37.69 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1721144361.A.9E3.html
→ nozomizo: 大師 07/16 23:57