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) ------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.org.tw), 來自: 101.139.133.88 (臺灣) ※ 文章網址: https://ptt.org.tw/Marginalman/M.1713316050.A.517
SecondRun: 太早 04/17 09:08