Ctrl K

Grandchildren of Even Ancestors

Medium
You are given the root of a binary tree. Add up the values of every node whose grandparent (the parent of its parent) exists and holds an even number. If no node qualifies, return 0.
Example 1
root=tree_node([4, 3, 5, 1, 9, None, 7]) → 17

The root 4 is even and its grandchildren are 1, 9 and 7: 1 + 9 + 7 = 17. No other node has grandchildren.

Example 2
root=tree_node([3, 6, None, 2, 8, 5]) → 5

The root 3 is odd, so its grandchildren 2 and 8 do not count. The even node 6 has one grandchild, 5, so the answer is 5.

Example 3
root=tree_node([10, 20]) → 0

The tree has only two levels, so nobody has a grandchild.

Constraints
  • 1 ≤ number of nodes ≤ 10⁴
  • 1 ≤ Node.val ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Tree Seen From the Right MediumTree Columns, Top Down MediumFirst Value on the Lowest Row MediumLargest Value on Each Tree Level MediumInsert a Tree Level Medium
loading Python…
Input
root=tree_node([4, 3, 5, 1, 9, None, 7])
Expected
17

Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.