오늘도...힘차게...퐈이팅...
오늘은 Root에서 Leaf까지 한 번 거칠 때 마다 10씩 곱해져서 더해진 숫자를 모두 더하는 (?) 문제이다.
DFS를 사용하여 해결하였다.
# 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 sumNumbers(self, root: Optional[TreeNode]) -> int:
def dfs(root, res):
if not root:
return 0
res = res * 10 + root.val
if not root.left and not root.right:
return res
return dfs(root.left, res) + dfs(root.right, res)
return dfs(root, 0)
와! 99 Beat 너무 짜릿하다!
'Leetcode' 카테고리의 다른 글
Leetcode 118. Pascal's Triangle (0) | 2021.11.06 |
---|---|
441. Arranging Coins (0) | 2021.11.05 |
232. Implement Queue using Stacks (0) | 2021.11.02 |
83. Remove Duplicates from Sorted List (0) | 2021.10.30 |
Leetcode 226. Invert Binary Tree (0) | 2021.10.26 |