[leetcode] 1315. Sum of Nodes with Even-Valued Grandparent

Description

Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)

If there are no nodes with an even-valued grandparent, return 0.

Example 1:
在这里插入图片描述

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

分析

题目的意思是:找出当前结点的祖父结点是偶数的结点,并求和。如果是父结点比较好做,如果是祖父结点呢,如果能够想到在传参数的时候把祖父结点也当成参数传下去就好办了,剩下的就是递归和满足条件求和了。如果想不到就尴尬了。我看了一下其他人的解法,也可以直接把祖父结点的值当成参数传进去,也能做出来。

代码

# 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 solve(self,root,parent,grandParent):
        if(root is None):
            return
        self.solve(root.left,root,parent)
        self.solve(root.right,root,parent)
        if(root and grandParent and grandParent.val%2==0):
            self.res+=root.val
        

    def sumEvenGrandparent(self, root: TreeNode) -> int:
        self.res=0
        self.solve(root,None,None)
        return self.res

参考文献

[LeetCode] Distribute Candies 分糖果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值