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

看板Marginalman作者 (caster )時間1年前 (2024/04/15 09:34), 編輯推噓0(001)
留言1則, 1人參與, 1年前最新討論串119/1548 (看更多)
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : 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) : ------------------------------------ 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 sumNumbers(self, root: Optional[TreeNode]) -> int: def dfs(node,temp): nonlocal result if not node: return if not node.left and not node.right: result += temp*10 + node.val return dfs(node.left,temp*10+node.val) dfs(node.right,temp*10+node.val) result = 0 dfs(root,0) return result 思路差不多 本來想開個list紀錄節點再計算 後來想想直接記錄數字和就好 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.136.65.164 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1713144844.A.38C.html

04/15 11:28, 1年前 , 1F
大師
04/15 11:28, 1F
文章代碼(AID): #1c78GCEC (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c78GCEC (Marginalman)