LeetCode/2020 LeetCoding Challenge

LeetCode. Sum Root to Leaf Numbers

벤진[Benzene] 2020. 6. 27. 02:10

Problem:

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

 

-Summary-

Used recursive 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: TreeNode) -> int:
        self.res = 0
        self.dfs(root, 0)
        return self.res
    
    def dfs(self, root, value):
        if root:
            self.dfs(root.left, value*10 + root.val)
            self.dfs(root.right, value*10 + root.val)
            
            if not root.left and not root.right:
                self.res += value*10 + root.val

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]