소프트웨어에 대한 모든 것

LeetCode 풀기 - 1022. Sum of Root To Leaf Binary Numbers 본문

알고리즘/LeetCode

LeetCode 풀기 - 1022. Sum of Root To Leaf Binary Numbers

앤테바 2022. 1. 11. 20:36
반응형

1022. Sum of Root To Leaf Binary Numbers

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

 

Sum of Root To Leaf Binary Numbers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) 재귀

# 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 sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        leaf_bins = []
        def recur(node, bins):
            if node is None:
                return
            
            recur(node.left, bins + str(node.val))
            
            if node.left is None and node.right is None:
                leaf_bins.append(bins + str(node.val))
                return
            
            recur(node.right, bins + str(node.val))
        
        recur(root, '')
        return sum([int(leaf, base=2) for leaf in leaf_bins])

 

반응형
Comments