【力扣】1315:祖父节点值为偶数的节点和 | 递归 |DFS

题目描述

给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:

该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)
如果不存在祖父节点值为偶数的节点,那么返回 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%的用户

发布了317 篇原创文章 · 获赞 44 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Heart_for_Ling/article/details/105617731