码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1315. Sum of Nodes with Even-Valued Grandparent

时间:2020-01-12 17:53:44      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:nbsp   style   xpl   elf   code   obj   src   exist   div   

题目如下:

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
        

【leetcode】1315. Sum of Nodes with Even-Valued Grandparent

标签:nbsp   style   xpl   elf   code   obj   src   exist   div   

原文地址:https://www.cnblogs.com/seyjs/p/12183225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!