Sponsored
Sponsored
This approach uses a depth-first search traversal to keep track of the current node's parent and grandparent values. If the grandparent's value is even, the node's value is added to the sum.
We initiate the DFS with the root, setting initial parent and grandparent values as null or zero.
Time Complexity: O(n) where n is the number of nodes. Each node is visited once.
Space Complexity: O(h) where h is the height of the tree due to the recursion stack.
1function TreeNode(val, left = null, right = null) {
2 this.val = val;
3 this.left = left;
4 this.right = right;
5}
6
7var sumEvenGrandparent = function(root) {
8 function dfs(node, parent, grandparent) {
9 if (!node) return 0;
10 let total = 0;
11 if (grandparent && grandparent.val % 2 === 0) {
12 total += node.val;
13 }
14 total += dfs(node.left, node, parent);
15 total += dfs(node.right, node, parent);
16 return total;
17 }
18 return dfs(root, null, null);
19};
This JavaScript solution leverages recursive depth-first traversal to calculate the desired node sum. As we navigate the tree, we account for whether each node has an even-valued grandparent.
Utilizing an iterative method with breadth-first traversal (via a queue) enables level-wise examination of tree nodes. This format offers insight into parent-grandchild relations by leveraging node attributes over iteration.
Time Complexity: O(n), where n is the count of nodes due to single node examination.
Space Complexity: O(w), w being the maximum width of the tree, accounting for queue storage.
This Python implementation leverages a queue to perform level-order traversal. Pairs of node, parent, grandparent are used to track lineage and compute the sum for nodes with even-valued grandparents.