leetcode1315. Sum of Nodes with Even-Valued Grandparent
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1315. 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
and10^4
.- The value of nodes is between
1
and100
.
解题思路:遍历树,递归函数的参数带上父节点的值即可。
代码如下:
# 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
以上是关于leetcode1315. Sum of Nodes with Even-Valued Grandparent的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 1315. Sum of Nodes with Even-Valued Grandparent
[LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent