Leetcode 1243 Solution

This article provides solution to leetcode question 1243 (sum-of-nodes-with-even-valued-grandparent)

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent

Solution

# 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:
        stack = []
        ans = 0

        def dfs(node):
            nonlocal ans
            nonlocal stack

            if not node:
                return

            if len(stack) >= 2 and (stack[-2] % 2 == 0):
                ans += node.val

            stack.append(node.val)
            dfs(node.left)
            dfs(node.right)
            stack.pop()

        dfs(root)

        return ans