Thursday, August 20, 2015

Leetcode 129. Sum Root to Leaf Numbers

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

Solution:
# T:O(n) S:O(h)
class Solution:
    # @param root, a tree node
    # @return an integer
    def sumNumbers(self, root):
        return self.sumNumbersRecu(root, 0)
    def sumNumbersRecu(self, root, num):
        if root is None:
            return 0 
        if root.left is None and root.right is None:
            return num * 10 + root.val
        return self.sumNumbersRecu(root.left, num * 10 + root.val) +\
   self.sumNumbersRecu(root.right, num * 10 + root.val)
Run Time: 40 ms

No comments:

Post a Comment