1622. Elder Divisible Total

A family-tree app stores each person as a node of a binary tree whose value is an age score (it may be negative). A node qualifies when it has a grandparent (the parent of its parent) and the grandparent's value is divisible by the given integer k, meaning the remainder is exactly zero, so negative and zero values that are multiples of k count.

Given the root of the tree and k, return the sum of the values of all qualifying nodes as a long. A node with no grandparent never qualifies; a tree with no qualifying node gives 0.

Visit every node once while carrying its parent and grandparent along, and avoid deep recursion since the tree can be a long chain. Target complexity: O(n) time, O(n) space.

Example 1

Input:
root = [6,2,5,1,8,3,4], k = 2
Output:
16
Explanation:

Grandparent 6 is a multiple of 2; its grandchildren are 1, 8, 3 and 4, so the total is 16.

Example 2

Input:
root = [9,-3,7,6], k = 3
Output:
6
Explanation:

Node 6 has grandparent 9, a multiple of 3; no other node has a grandparent, so the answer is 6.

Example 3

Input:
root = [4,1,2,null,null,3,5], k = 7
Output:
0
Explanation:

Grandparent 4 is not a multiple of 7, so nothing is counted and the answer is 0.

Constraints

1 ≤ nodes ≤ 1000

-104 ≤ Node.val ≤ 104

1 ≤ k ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…