描述
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.
Note:
The number of nodes in the tree is between 1 and 10^4.
The value of nodes is between 1 and 100.
解析
根据题意,只需要找出该节点有爷爷节点且爷爷节点是偶数,就将该节点的值加入 res 中,使用 DFS 遍历所有节点之后即可得到结果。第一种解法是从下往上,代码比较简洁。第二种解法是从上往下比较好理解,只是代码有些冗余。
解答
class Solution(object):
def sumEvenGrandparent(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(current, father, grand):
if not current:
return
if grand and grand.val % 2 == 0:
self.res += current.val
dfs(current.left, current, father)
dfs(current.right, current, father)
self.res = 0
dfs(root, None, None)
return self.res
运行结果
Runtime: 100 ms, faster than 75.60% of Python online submissions for Sum of Nodes with Even-Valued Grandparent.
Memory Usage: 20.9 MB, less than 46.39% of Python online submissions for Sum of Nodes with Even-Valued Grandparent.
解答
class Solution(object):
def sumEvenGrandparent(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def grandparent(root):
if not root or (not root.left and not root.right):
return
if root.left and root.left.left and root.val % 2 == 0:
self.res += root.left.left.val
if root.left and root.left.right and root.val % 2 == 0:
self.res += root.left.right.val
grandparent(root.left)
if root.right and root.right.left and root.val % 2 == 0:
self.res += root.right.left.val
if root.right and root.right.right and root.val % 2 == 0:
self.res += root.right.right.val
grandparent(root.right)
self.res = 0
grandparent(root)
return self.res
运行结果
Runtime: 116 ms, faster than 26.51% of Python online submissions for Sum of Nodes with Even-Valued Grandparent.
Memory Usage: 21 MB, less than 46.39% of Python online submissions for Sum of Nodes with Even-Valued Grandparent.
原题链接:leetcode.com/problems/su…
您的支持是我最大的动力