题目描述
给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:
该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)
如果不存在祖父节点值为偶数的节点,那么返回 0 。
算法思路
深度优先搜索
方法内的变量+辅助函数
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
self.res=0
def helper(root,g='',p=''):
if not root:return 0
if g and g.val%2==0:
self.res+=root.val
helper(root.left,p,root)
helper(root.right,p,root)
return self.res
return helper(root)
执行用时 :112 ms, 在所有 Python3 提交中击败了71.46%的用户
内存消耗 :17.2 MB, 在所有 Python3 提交中击败了100.00%的用户
做了一点优化,删掉了辅助函数以及独立的变量self.res
class Solution:
def sumEvenGrandparent(self, root,res=0,g='',p='') -> int:
if not root:return res
if g and g.val%2==0:
res+=root.val
res=self.sumEvenGrandparent(root.left,res,p,root)
res=self.sumEvenGrandparent(root.right,res,p,root)
return res
执行用时 :116 ms, 在所有 Python3 提交中击败了59.70%的用户
内存消耗 :17.2 MB, 在所有 Python3 提交中击败了100.00%的用户