Sum of Even-Valued Nodes
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.
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.
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.val for all nodes in the tree where val is an even number.root is null) should return 0.Examples
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.
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.
Example 3
Input:
root = [1]
Output:
0
Note:
The only node has value 1, which is odd. The sum of even values is 0.
Example 4
Input:
root = null
Output:
0
Note:
The tree is empty, so there are no even-valued nodes to sum.
Constraints
0 and 10^4.-10^5 <= Node.val <= 10^5.Loading editor...