当前位置: 代码迷 >> 综合 >> Leetcode 129. Sum Root to Leaf Numbers(python)
  详细解决方案

Leetcode 129. Sum Root to Leaf Numbers(python)

热度:65   发布时间:2023-11-26 07:51:31.0

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.

在这里插入图片描述
二刷:利用nonlocal

class Solution:def sumNumbers(self, root: Optional[TreeNode]) -> int:ans = 0def dfs(node,curr):nonlocal ansif not node.left and not node.right:curr = curr * 10 + node.valans += currreturnif node.left:dfs(node.left,curr * 10 + node.val)if node.right:dfs(node.right,curr * 10 + node.val)dfs(root,0)return ans

解法1:DFS直接计算

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

class Solution(object):def sumNumbers(self, root):""":type root: TreeNode:rtype: int"""def sumN(root,preSum):if not root:return 0preSum = preSum*10 + root.valif not root.left and not root.right:return preSumreturn 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)))returnif root.left:getnumber(root.left,number+str(root.val))if root.right:getnumber(root.right,number+str(root.val))if not root:return 0numberlist = []getnumber(root,'')return sum(numberlist)

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

  相关解决方案