[LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent
Updated:
Sum of Nodes with Even-Valued Grandparent
LeetCode λ¬Έμ λ₯Ό νλ€κ° λκΌλλ° Input μ΄ μΉμ νμ§ μλ€. μ΄ λ¬Έμ λ Input: root = [6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5]
μΌλ‘λ§ λμ΄μκ³ μ λ΅ μ½λλ μ΄λ―Έ Binary Tree κ° κ΅¬ν λ μνλ₯Ό μ μ λ‘ μμ±ν΄μΌ νλ€.
κ°μ²΄λ‘ ꡬννμ§ μκ³ λ¨μν root λ°°μ΄μ index λ₯Ό ν΅ν΄μ ν μ λ μλλ° λ§μ΄λ€.
μ΄λ° μμ νΈλ¦¬ ꡬνμ μ°μ΅νλΌλ λ»μΈκ°.. μ¬μ€ κ°μ²΄λ‘ νΈλ¦¬ λ§λλ 건 ν λ²λ μν΄λ³΄κΈ΄ νλ€.. μ΄ κΈ°νμ ν λ² λ§λ€μ΄μ μνλ ν΄λ΄μΌκ² λ€.
μ£Όμ΄μ§ νΈλ¦¬λ₯Ό μννλ©΄μ μ‘°λΆλͺ¨ λ Έλκ° μ§μ μΈ κ²½μ° νμ¬ λ Έλμ κ°μ λνλ©΄ λλ€.
νΈλ¦¬λ μ΄λ―Έ ꡬνμ΄ λμ΄μ μ£Όμ΄μ§κΈ° λλ¬Έμ DFS μ½λλ§ μ§λ©΄ λλ€.
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def DFS(node, parent, grand, answer):
if not node:
return 0
if grand and grand.val % 2 == 0:
answer.append(node.val)
DFS(node.left, node, parent, answer)
DFS(node.right, node, parent, answer)
answer = []
DFS(root, None, None, answer)
return sum(answer)
Leave a comment