Python解法

二叉树根节点到叶子节点的所有路径和

http://www.nowcoder.com/questionTerminal/185a87cd29eb42049132aed873273e83

思路:找到所有根节点到叶节点的路径并存储,然后进行对每条路径求和。时间复杂度:二叉树遍历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


全部评论

相关推荐

蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务