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
哀 窝好烂