Python algorithm using recursion, 50ms

  • 0
    class Solution:
        # @param root, a tree node
        # @return an integer
        def sumNumbers(self, root):
            if root is None:
                return 0
            res = self.sumNum(root,0)
            return res
        def sumNum(self, root, mid_res):
            if root is None:
                return mid_res
            mid_res += root.val
            left = root.left
            right = root.right
            if left is None and right is None:
                return mid_res
            if left is not None and right is None:
                res = self.sumNum(left,mid_res*10)
                return res
            if right is not None and left is None:
                res = self.sumNum(right,mid_res*10)
                return res
            res = self.sumNum(left,mid_res*10) + self.sumNum(right,mid_res*10)
            return res

Log in to reply

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