Simple Python DFS Solution


  • 0
    M
        def sumNumbers(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            paths = []
            def getPaths(node, s):
                if not node:
                    return
                if not node.left and not node.right:
                    paths.append(s + str(node.val))
                    return
                if node.left:
                    getPaths(node.left, s + str(node.val))
                if node.right:
                    getPaths(node.right, s + str(node.val))
            
            getPaths(root, '')
            return sum(map(int, paths))
    

Log in to reply
 

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