9 lines O(n) Simple Python


  • 0
    def pathSum(self, nums):
        res = 0
        seen = collections.defaultdict(int)
        while nums:
            node = nums.pop()
            level, pos, val = node / 100, (node / 10) % 10, node % 10
            seen[level, pos] = seen[level+1, pos*2] + seen[level+1, pos*2-1]
            if seen[level, pos] == 0:   seen[level, pos] = 1
            res += val * seen[level, pos]
        return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.