zoukankan      html  css  js  c++  java
  • 【leetcode】1315. Sum of Nodes with Even-Valued Grandparent

    题目如下:

    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(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        res = 0
        def sumEvenGrandparent(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.res = 0
    
            def recursive(node,parent_val):
                if node.left != None:
                    if parent_val != None and parent_val % 2 == 0:
                        self.res += node.left.val
                    recursive(node.left,node.val)
    
                if node.right != None:
                    if parent_val != None and parent_val % 2 == 0:
                        self.res += node.right.val
                    recursive(node.right,node.val)
    
            recursive(root,None)
            return self.res
            
  • 相关阅读:
    使用weave管理docker网络
    为docker配置固定ip
    Building good docker images
    使用curl命令获取文件下载速度
    吐槽Java
    Kubernetes 中的服务发现与负载均衡(转)
    Kubernetes系列之介绍篇(转)
    top命令中的wa指标(转)
    uwsgi常用参数详解(转)
    Unix域套接字-Unix Domain Socket(转)
  • 原文地址:https://www.cnblogs.com/seyjs/p/12183225.html
Copyright © 2011-2022 走看看