https://leetcode.com/problems/cousins-in-binary-tree-ii
2641. Cousins in Binary Tree II
昨天的解完後看Similar Questions看到這題 今天就出了
打算用跟昨天一樣的解法 但後面測資錯了 有大師能幫看是哪邊有問題嗎 ((
用層數與父值當key 同父的就相加
之後把同一層key != parent的加起來
測資17的output第15層錯了 特調後測資18的12跟14層錯了 後面大概也都過不了
# 修改後的Code在最底下
Python Code:
class Solution:
def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[
TreeNode]:
def c(node: TreeNode, res: defaultdict, level: int, parent: int):
res[level][parent] += node.val
if node.left:
c(node.left, res, level+1, node.val)
if node.right:
c(node.right, res, level+1, node.val)
def u(node: TreeNode, res: defaultdict, level: int, parent: int):
if node.left:
u(node.left, res, level+1, node.val)
if node.right:
u(node.right, res, level+1, node.val)
node.val = sum(v for k, v in res[level].items() if k != parent)
res = defaultdict(lambda: defaultdict(int))
c(root, res, 1, 0)
# print(json.dumps({k: dict(v) for k, v in res.items()}))
u(root, res, 1, 0)
return root
哀 窩好爛