leetcode 1315. Sum of Nodes with Even-Valued Grandparent(python)

描述

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:

avatar

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):
   

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/115267386
今日推荐