思路:找到所有根节点到叶节点的路径并存储,然后进行对每条路径求和。时间复杂度:二叉树遍历O(n)+路径求和O(n)

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

#
# 
# @param root TreeNode类 
# @return int整型
#
class Solution:

    def sumNumbers(self , root ):
        res = self.binaryTreePaths(root)
        sums = 0
        for i in range(len(res)):
            sums = sums+int(res[i])
        return sums


    def binaryTreePaths(self, root: TreeNode):
        if not root:
            return []
        result = []

        def dfs(root, auxiliary):
            if not root:
                return
            if not root.left and not root.right:
                auxiliary_auxiliary = auxiliary + str(root.val)
                result.append(auxiliary_auxiliary)
            dfs(root.left, auxiliary + str(root.val))
            dfs(root.right, auxiliary + str(root.val))

        dfs(root, '')
        return result