Sum of Grandchildren of Even-ID Campaigns
Inmobi manages a vast and intricate network of ad campaigns, often organized in hierarchical structures. Each node in this hierarchy represents a unique campaign, identified by a numeric ID. Understanding specific relationships within this structure is crucial for targeted analysis and optimization. This problem challenges you to identify and aggregate data based on a particular multi-generational relationship: summing the IDs of campaigns that are 'grandchildren' of campaigns with even numeric IDs.
You are given the root of a binary tree representing an ad campaign hierarchy. Each TreeNode has a val property which is a unique campaign ID. Your task is to implement a function sumGrandchildrenOfEvenIdCampaigns that calculates the sum of val for all nodes that have an even-valued grandparent.
Input:
root: A TreeNode | null representing the root of the binary tree. Each node has a val (number), left (TreeNode | null), and right (TreeNode | null).Output:
number representing the total sum of val for all nodes that are grandchildren of an even-ID campaign.val is an even number.A is a node C such that A is the parent of B, and B is the parent of C.root is null, or the tree does not contain any even-ID campaigns with grandchildren, the function should return 0.val) will be positive integers.Examples
Example 1
Input:
root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output:
18
Note:
Campaign 6 (even ID) has left child 7 (parent of 2, 7) and right child 8 (parent of 1, 3). Grandchildren of 6 are 2, 7, 1, 3. Campaign 8 (even ID) has left child 1 (parent of 9) and right child 3 (parent of 5). Grandchildren of 8 are 9, 5. Total sum = 2+7+1+3+9+5 = 27. Correction: The provided example array structure implies specific children. For root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]:
6 (even)
/
7 8 (even)
/ \ /
2 7 1 3
/\ /\ /\ /
9 _ 1 4 _ _ 5
Grandchildren of 6: (via 7) -> 2, 7. (via 8) -> 1, 3. Sum = 2+7+1+3 = 13.
Grandchildren of 8: (via 1) -> 9. (via 3) -> 5. Sum = 9+5 = 14.
Total sum = 13 + 14 = 27. Re-evaluating example. The explanation for the first example is incorrect; let's stick to the tree structure implied by the array and correct the explanation.
Example 2
Input:
root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output:
27
Note:
Campaign 6 (even ID) has grandchildren 2, 7, 1, 3. Campaign 8 (even ID) has grandchildren 9, 5. Total sum = 2+7+1+3+9+5 = 27.
Example 3
Input:
root = [2,1,3,4,5,6,7]
Output:
22
Note:
Campaign 2 (even ID) has grandchildren 4, 5, 6, 7. Total sum = 4+5+6+7 = 22.
Example 4
Input:
root = [1,2,3,4,5,6,7]
Output:
0
Note:
No campaign with an even ID has any grandchildren in this hierarchy.
Constraints
val) will be between 1 and 10^5.Loading editor...