classSolution: defsumOfGrandson(self, root: TreeNode) -> int: ret = 0 if root.left: if root.left.left: ret += root.left.left.val if root.left.right: ret += root.left.right.val if root.right: if root.right.left: ret += root.right.left.val if root.right.right: ret += root.right.right.val return ret defsumEvenGrandparent(self, root: TreeNode) -> int: ret = 0 ifnot root: return0 if root.val % 2 == 0: ret += self.sumOfGrandson(root) ret += self.sumEvenGrandparent(root.left) + self.sumEvenGrandparent(root.right) return ret
One-line 算法
Intuition
Let children know who their grandparent is.
Explanation
Assume root has parent.val = 1 and grandparent.val = 1.
Recursive iterate the whole tree and pass on the value of parent and grandparent.
Count the root.val when grandparant if odd-valued.