# 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 sumEvenGrandparent(self, root: TreeNode) -> int:
'''
找到所有值为偶数的节点,并对这些节点的孙子节点(即子节点的子节点)统计答案
'''
q = collections.deque([root])
ans = 0
while len(q) > 0:
node = q.popleft()
if node.val % 2 == 0:
if node.left:
if node.left.left:
ans += node.left.left.val
if node.left.right:
ans += node.left.right.val
if node.right:
if node.right.left:
ans += node.right.left.val
if node.right.right:
ans += node.right.right.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return ans
# 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 sumEvenGrandparent(self, root: TreeNode) -> int:
ans = 0
def dfs(grandparent, parent, node):
if not node:
return
if grandparent.val % 2 == 0:
nonlocal ans
ans += node.val
dfs(parent, node, node.left)
dfs(parent, node, node.right)
if root.left:
dfs(root, root.left, root.left.left)
dfs(root, root.left, root.left.right)
if root.right:
dfs(root, root.right, root.right.left)
dfs(root, root.right, root.right.right)
return ans