[LeetCode] 129. Sum Root to Leaf Numbers

김민우·2023년 3월 15일
0

알고리즘

목록 보기
157/189

- Problem

129. Sum Root to Leaf Numbers


- 내 풀이 (BFS)

# 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(node, cur) -> int:
            if not node:
                return 0

            cur = (cur * 10) + node.val

            if not node.left and not node.right:
                return cur
            
            return dfs(node.left, cur) + dfs(node.right, cur)
        
        return dfs(root, 0)

- 결과

profile
Pay it forward.

0개의 댓글