Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster )時間1年前 (2024/04/17 18:22), 編輯推噓6(602)
留言8則, 6人參與, 1年前最新討論串128/1548 (看更多)
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : https://leetcode.com/problems/smallest-string-starting-from-leaf/description/ : 988. Smallest String Starting From Leaf : 給你一個val範圍在 [0:25] 的二元樹,這些val分別對應 [a:z],找出從葉子節點到跟 : 節點路徑表示的最小字典順序字串。 : 思路: : 1.dfs整個樹,過程紀錄path,遇到葉子節點就比大小並把答案更新成比較小的。 : py code: : ------------------------------------------- : class Solution: : def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: : self.res = "~" : self.dfs(root, "") : return self.res : def dfs(self, root: Optional[TreeNode], s) -> str: : if not root: : return : s = chr(ord('a') + root.val) + s : if not root.left and not root.right: : self.res = min(self.res, s) : self.dfs(root.left, s) : self.dfs(root.right, s) : ------------------------------------------- 思路差不多 Python Code: # 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 smallestFromLeaf(self, root: Optional[TreeNode]) -> str: def dfs(node,s): nonlocal result if not node: return if not node.left and not node.right: result.append(chr(ord("a")+node.val)+s) dfs(node.left,chr(ord("a")+node.val)+s) dfs(node.right,chr(ord("a")+node.val)+s) result = [] dfs(root,"") result.sort() return result[0] 一開始沒仔細看題目 還以為要確認是否照順序 姆咪 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.137.148 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1713349323.A.BA8.html

04/17 18:23, 1年前 , 1F
大師
04/17 18:23, 1F

04/17 18:24, 1年前 , 2F
我一開始不知道漬點序是什麼 害我搞超級久 我吐了
04/17 18:24, 2F

04/17 18:24, 1年前 , 3F
大師
04/17 18:24, 3F

04/17 18:25, 1年前 , 4F
我一開始想說還要確認是否遞增遞減 後來才發現不用
04/17 18:25, 4F

04/17 18:26, 1年前 , 5F
大師
04/17 18:26, 5F

04/17 18:26, 1年前 , 6F
寶 你要內推我
04/17 18:26, 6F

04/17 18:27, 1年前 , 7F
你本科系在那講幹話
04/17 18:27, 7F

04/17 18:41, 1年前 , 8F
別捲了
04/17 18:41, 8F
文章代碼(AID): #1c7wBBke (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c7wBBke (Marginalman)