Leetcode 129. Sum Root to Leaf Numbers(python)

Leetcode 129. Sum Root to Leaf Numbers

  • 题目
  • 解法1:DFS直接计算
  • 解法2:DFS+list

题目

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.An example is the root-to-leaf path 1->2->3 which represents the number 123.Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Leetcode 129. Sum Root to Leaf Numbers(python)_第1张图片

解法1:DFS直接计算

这种方法看起来方便不过好像比较难理解,推荐第二种方法

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def sumN(root,preSum):
            if not root:
                return 0
            preSum = preSum*10 + root.val
            if not root.left and not root.right:
                return preSum
            return sumN(root.left,preSum) + sumN(root.right,preSum)
    
        return sumN(root,0)

时间复杂度:O(N), N是节点的个数,因为每个节点都会访问一遍
空间复杂度:O(1)

解法2:DFS+list

用dfs将所有数字先append到list中,最后求sum,这种方法比较直观

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def getnumber(root,number):
            if not root.left and not root.right:
                numberlist.append(int(number+str(root.val)))
                return
            if root.left:
                getnumber(root.left,number+str(root.val))
            if root.right:
                getnumber(root.right,number+str(root.val))
        if not root:
            return 0
        numberlist = []
        getnumber(root,'')
        return sum(numberlist)

时间复杂度:O(N), N是节点的个数,因为每个节点都会访问一遍。对比第一种解法,这个时间复杂度按理来讲是一样的,但是提交的结果比第一种方法快很多,有点不解,有想法的同学欢迎评论
空间复杂度:O(N),空间复杂度比解法1大,但是提交结果确是一样的,同样有点疑惑

你可能感兴趣的:(Leetcode,DFS,leetcode,算法,python)