[leetcode] 1315. Sum of Nodes with Even-Valued Grandparent
程序员文章站
2022-07-15 11:22:36
...
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