Sum Nodes with an Even-Valued Grandparent
Problem statement
Given a binary tree, return the sum of every node whose grandparent exists and has an even value.
A grandparent is the parent of a node's parent. Nodes at depth zero or one never contribute.
Function
sumEvenGrandparent(root: TreeNode) → intExamples
Example 1
root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]return = 18The eligible descendants sum to 18.
Example 2
root = [1]return = 0The root has no grandparent.
Example 3
root = [2,1,3,4,5,6,7]return = 22All four grandchildren have the even root as grandparent.
Constraints
- The tree has 1 to 10000 nodes.
0 <= node.val <= 100.