Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/10/23 09:12), 編輯推噓1(102)
留言3則, 3人參與, 1年前最新討論串1028/1548 (看更多)
2641. Cousins in Binary Tree II ## 思路 BFS 每一層都用Hashtable記錄同父節點的和 然後再更新值 (= 整層總和 - 同父節點的和) ## Code ```python class Solution: def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: root.val = 0 queue = deque() if root.left: queue.append((root, root.left)) if root.right: queue.append((root, root.right)) while queue: total = 0 table = defaultdict(int) for _ in range(len(queue)): parent, node = queue.popleft() total += node.val table[parent] += node.val if node.left: queue.append((node, node.left)) if node.right: queue.append((node, node.right)) for parent in table: if parent.left: parent.left.val = total - table[parent] if parent.right: parent.right.val = total - table[parent] return root ``` -- https://i.imgur.com/kyBhy6o.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.50 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729645939.A.93E.html

10/23 09:13, 1年前 , 1F
別卷了
10/23 09:13, 1F

10/23 09:15, 1年前 , 2F
早早早
10/23 09:15, 2F

10/23 09:20, 1年前 , 3F
10/23 09:20, 3F
文章代碼(AID): #1d64rpa- (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d64rpa- (Marginalman)