【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
        
posted @ 2020-01-12 17:22  seyjs  阅读(456)  评论(0编辑  收藏  举报