Sum of Nodes with Even-Valued Grandparent — LeetCode 1315 Python Solution
MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
- Problem
- #1315
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
- Output
- 18
- Explanation
- The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
Python solution
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(root: TreeNode, x: int) -> int:
if root is None:
return 0
ans = dfs(root.left, root.val) + dfs(root.right, root.val)
if x % 2 == 0:
if root.left:
ans += root.left.val
if root.right:
ans += root.right.val
return ans
return dfs(root, 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1315. Sum of Nodes with Even-Valued Grandparent is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1315. Sum of Nodes with Even-Valued Grandparent?
- LeetCode 1315. Sum of Nodes with Even-Valued Grandparent is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1315. Sum of Nodes with Even-Valued Grandparent?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1315. Sum of Nodes with Even-Valued Grandparent?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1315. Sum of Nodes with Even-Valued Grandparent cover?
- LeetCode 1315. Sum of Nodes with Even-Valued Grandparent is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.