Skip to content

129. Sum Root to Leaf Numbers #153

@zeikar

Description

@zeikar

Problem link

https://leetcode.com/problems/sum-root-to-leaf-numbers

Problem Summary

루트부터 리프 노드까지를 이었을 때 생기는 수를 다 더하는 문제

Solution

재귀적으로 구현하면 된다. 자식 노드로 내려갈 때 현재 값에 10을 계속 곱해주면서 더하면 된다.
보통 재귀적으로 합을 구할 때와 순서가 반대라서 약간 헷갈리긴 한다

Source Code

# 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 getSum(node, s):
            if not node:
                return 0
            if not node.left and not node.right:
                return s * 10 + node.val

            return getSum(node.left, s * 10 + node.val) + getSum(
                node.right, s * 10 + node.val
            )

        return getSum(root, 0)

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions