파비의 매일매일 공부기록

2023.03.14 Today's Challenge 본문

Problem Solving/LeetCode

2023.03.14 Today's Challenge

fabichoi 2023. 3. 14. 23:45

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

 

Sum Root to Leaf Numbers - LeetCode

Can you solve this real interview question? Sum Root to Leaf Numbers - You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path 1 -> 2 -> 3 repr

leetcode.com

전형적인 dfs 문제

class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        self.result = 0

        def dfs(node, curr_sum):
            if not node:
                return
            curr_sum = curr_sum * 10 + node.val

            if not node.left and not node.right:
                self.result += curr_sum
                return

            dfs(node.left, curr_sum)
            dfs(node.right, curr_sum)
        
        dfs(root, 0)
        return self.result
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.03.16 Today's Challenge  (0) 2023.03.16
2023.03.15 Today's Challenge  (0) 2023.03.15
2023.03.13 Today's Challenge  (0) 2023.03.13
2023.03.12 Today's Challenge  (0) 2023.03.12
2023.03.11 Today's Challenge  (0) 2023.03.11
Comments