Python recursive solution


  • 0
    R
    class Solution(object):
    def __init__(self):
        self.ans=0
    def helper(self,root,num):
        if not root:
            return None
        else:
            num+=str(root.val)
            l=self.helper(root.left,num)
            r=self.helper(root.right,num)
            if not l and not r:
                self.ans+=int(num)
            return self.ans
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        else:
            return self.helper(root,"")

Log in to reply
 

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