Frontend School

Sum of Even-Valued Nodes

DSA
easy

Sum of Even-Valued Nodes

Easy
Tree
Binary Tree
Depth-First Search
Breadth-First Search

Overview

In many data processing systems, trees are used to organize hierarchical data efficiently. Often, we need to aggregate specific types of data points within these structures. This problem asks you to calculate the sum of values from nodes in a binary tree that meet a specific criterion: having an even value. This is a fundamental operation that demonstrates your ability to traverse a tree and apply conditional logic.

What you need to do / Task

Implement a function sumEvenValuedNodes that takes the root of a binary tree and returns the sum of the values of all nodes whose val is an even number.

Input & output

  • Input: root: A TreeNode representing the root of a binary tree. Each TreeNode has an integer val, a left child TreeNode, and a right child TreeNode. left and right can be null for leaf nodes.
  • Output: An integer representing the total sum of val for all nodes in the tree where val is an even number.

Clarifications

  • An empty tree (i.e., root is null) should return 0.
  • Node values can be positive, negative, or zero. Zero is considered an even number.

Examples

1

Example 1

Input:

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

Output:

12

Note:

The even-valued nodes are 2, 4, and 6. Their sum is 2 + 4 + 6 = 12.

2

Example 2

Input:

root = [2,1,4,null,null,3,5]

Output:

6

Note:

The even-valued nodes are 2 and 4. Their sum is 2 + 4 = 6.

3

Example 3

Input:

root = [1]

Output:

0

Note:

The only node has value 1, which is odd. The sum of even values is 0.

4

Example 4

Input:

root = null

Output:

0

Note:

The tree is empty, so there are no even-valued nodes to sum.

Constraints

Constraints & assumptions

  • The number of nodes in the tree is between 0 and 10^4.
  • -10^5 <= Node.val <= 10^5.
  • The tree structure is valid (no cycles).

What interviewers evaluate

  • Ability to correctly traverse a binary tree (e.g., using DFS or BFS).
  • Correctly handle base cases, such as an empty tree or leaf nodes.
  • Accurate accumulation of the sum based on the even-value condition.
  • Clean, readable, and well-structured code.

Loading editor...