语言:Python
描述:使用递归实现
1 def getList(self, node): 2 if node is None: 3 return [] 4 5 if node.left is None and node.right is None: 6 return [[node.val]] 7 8 result = [] 9 for item in self.getList(node.left): 10 result.append([node.val] + item) 11 12 for item in self.getList(node.right): 13 result.append([node.val] + item) 14 15 return result 16 17 def getNumByList(self, lst): 18 result = 0 19 for item in lst: 20 result *= 10 21 result += item 22 return result 23 24 def sumNumbers(self, root): 25 result = self.getList(root) 26 sum = 0 27 for item in result: 28 sum += self.getNumByList(item) 29 return sum
新的实现
1 class Solution: 2 # @param root, a tree node 3 # @return an integer 4 def sumPath(self, node, value): 5 if node is None: 6 return 0 7 8 value = value * 10 + node.val 9 if (node.left is None and node.right is None): 10 self.sum += value 11 12 self.sumPath(node.left, value) 13 self.sumPath(node.right, value) 14 15 def sumNumbers(self, root): 16 self.sum = 0 17 self.sumPath(root, 0) 18 19 return self.sum
#Leet Code# Root to leaf,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/mess4u/p/3835756.html