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.
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.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
9 this.val = val;
10 this.left = left;
11 this.right = right;
12 }
13}
14
15public class Solution {
16 public int SumEvenGrandparent(TreeNode root) {
17 Queue<(TreeNode, TreeNode, TreeNode)> queue = new Queue<(TreeNode, TreeNode, TreeNode)>();
18 queue.Enqueue((root, null, null));
19 int sum = 0;
20 while (queue.Count > 0) {
21 var (node, parent, grandparent) = queue.Dequeue();
22 if (node == null) continue;
23 if (grandparent != null && grandparent.val % 2 == 0) {
24 sum += node.val;
25 }
26 queue.Enqueue((node.left, node, parent));
27 queue.Enqueue((node.right, node, parent));
28 }
29 return sum;
30 }
31}
C# implements a traditional iterative approach via level-order traversal. Employing a queue, the pertinent nodes are examined level by level with accumulative operations on notes with even-valued grandparents.