DataScience trainee

Leetcode 1315. Sum of Nodes with Even-Valued Grandparent in Python3

Sum of Nodes with Even-Valued Grandparent


개요

  • 이번 포스팅은 파이썬 코딩테스트 연습문제 풀이입니다.
  • Leetcode 에 공개된 예제이며 링크는 아래와 같습니다.

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


코드

def sumEvenGrandparent(self, root: TreeNode) -> int:
    import copy

    def dfs(current, p, gp, answer):
        copy_tree = copy.copy(current)
        if gp != 0 and gp % 2 == 0:
            answer[0] += copy_tree.val

        if copy_tree.left != None:
            # p become gp and current val become p
            dfs(copy_tree.left, copy_tree.val, p, answer)
        if copy_tree.right != None:
            dfs(copy_tree.right, copy_tree.val, p, answer)

        return answer[0]

    return dfs(root, 0, 0, [0])

마치며

이번 포스팅은 Leetcode에 존재하는DFS 태크 중 난이도 Medium 에 해당하는 문제입니다.