Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.
A grandparent of a node is the parent of its parent if it exists. Think of it as traversing three generations in the tree: grandparent โ parent โ grandchild.
Example: If a node has value 6 (even), then all of its grandchildren's values should be included in our sum. We need to look two levels down from each even-valued node.
This problem tests your ability to track relationships across multiple levels of a tree structure while traversing efficiently.
Input & Output
Visualization
Time & Space Complexity
Visit each node exactly once during DFS traversal
Recursion stack depth equals tree height, O(log n) for balanced tree, O(n) worst case
Constraints
-
The number of nodes in the tree is in the range
[1, 104] -
1 โค Node.val โค 100 - Tree nodes are connected in a valid binary tree structure