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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 public int SumEvenGrandparent(TreeNode root) {
14 return DFS(root, null, null);
15 }
16
17 private int DFS(TreeNode node, TreeNode parent, TreeNode grandparent) {
18 if (node == null) return 0;
19 int sum = 0;
20 if (grandparent != null && grandparent.val % 2 == 0) {
21 sum += node.val;
22 }
23 sum += DFS(node.left, node, parent);
24 sum += DFS(node.right, node, parent);
25 return sum;
26 }
27}
In this C# implementation, the recursion pattern remains consistent, calculating the sum of nodes with even-valued grandparents using recursive depth-first exploration.
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.
The Java solution makes use of a queue structure to store node trios (node, parent, grandparent) for effective level-wise traversal. Each node checked is appended with appropriate ancestors in the queue, summing valid ones.