FastPrepSum Nodes with an Even-Valued Grandparent

Sum Nodes with an Even-Valued Grandparent

SambaNova Systems logoSambaNova Systems● MediumNEW GRADONSITE INTERVIEW
Learn

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) → int

Examples

Example 1

root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]return = 18

The eligible descendants sum to 18.

Example 2

root = [1]return = 0

The root has no grandparent.

Example 3

root = [2,1,3,4,5,6,7]return = 22

All four grandchildren have the even root as grandparent.

Constraints

  • The tree has 1 to 10000 nodes.
  • 0 <= node.val <= 100.

More SambaNova Systems problems

See SambaNova Systems hiring insights
public int sumEvenGrandparent(TreeNode root) {
    // write your code here
}
root[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
expected18
Checking account…