#1315
Sum of Nodes with Even-Valued Grandparent
MediumTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First Search (DFS)Recursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach improves efficiency by using a single traversal of the tree while keeping track of the parent and grandparent nodes. This avoids redundant checks and allows us to compute the sum in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Perform a depth-first traversal of the tree starting from the root.
- 2Step 2: For each node, check if its grandparent exists and if its value is even.
- 3Step 3: If the grandparent is even, add the current node's value to a running total.
- 4Step 4: Pass the current node as the parent and the previous parent as the grandparent for the next recursive calls.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def sumEvenGrandparent(self, root: TreeNode) -> int:
10 def dfs(node, parent, grandparent):
11 if not node:
12 return 0
13 total = 0
14 if grandparent and grandparent.val % 2 == 0:
15 total += node.val
16 total += dfs(node.left, node, parent) + dfs(node.right, node, parent)
17 return total
18 return dfs(root, None, None)ℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursion stack in the worst case (for a skewed tree).
- 1Understanding the relationship between nodes is crucial for tree problems.
- 2Recursion can simplify the traversal logic significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.