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

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/04/15 09:02), 1年前編輯推噓0(001)
留言1則, 1人參與, 1年前最新討論串118/1548 (看更多)
129. Sum Root to Leaf Numbers https://leetcode.com/problems/sum-root-to-leaf-numbers/description 給你一個二元樹,求出所有的root到leaf節點的路徑數字和。 思路: 1.普通dfs紀錄路徑中的數字和,如果當前點是leaf就累加。 py code: ------------------------------------ class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: self.res = 0 self.dfs(root, 0) return self.res def dfs(self, root: Optional[TreeNode], sum: int): if not root: return 0 sum = sum * 10 + root.val if not root.left and not root.right: self.res += sum self.dfs(root.left, sum) self.dfs(root.right, sum) ------------------------------------ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.110.205 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1713142922.A.9CD.html ※ 編輯: Rushia (101.138.110.205 臺灣), 04/15/2024 09:04:54

04/15 09:37, 1年前 , 1F
大濕
04/15 09:37, 1F
文章代碼(AID): #1c77oAdD (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c77oAdD (Marginalman)