#Leet Code# Root to leaf

时间:2025-01-08 18:35:02

语言:Python

描述:使用递归实现

     def getList(self, node):
if node is None:
return [] if node.left is None and node.right is None:
return [[node.val]] result = []
for item in self.getList(node.left):
result.append([node.val] + item) for item in self.getList(node.right):
result.append([node.val] + item) return result def getNumByList(self, lst):
result =
for item in lst:
result *=
result += item
return result def sumNumbers(self, root):
result = self.getList(root)
sum =
for item in result:
sum += self.getNumByList(item)
return sum

新的实现

 class Solution:
# @param root, a tree node
# @return an integer
def sumPath(self, node, value):
if node is None:
return value = value * + node.val
if (node.left is None and node.right is None):
self.sum += value self.sumPath(node.left, value)
self.sumPath(node.right, value) def sumNumbers(self, root):
self.sum =
self.sumPath(root, ) return self.sum