首页 > 代码库 > #Leet Code# Root to leaf

#Leet Code# Root to leaf

语言: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 result16 17     def getNumByList(self, lst):18         result = 019         for item in lst:20             result *= 1021             result += item22         return result23 24     def sumNumbers(self, root):25         result = self.getList(root)26         sum = 027         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 = http://www.mamicode.com/value * 10 + node.val 9         if (node.left is None and node.right is None):10             self.sum += value11          12         self.sumPath(node.left, value)13         self.sumPath(node.right, value)14 15     def sumNumbers(self, root):16         self.sum = 017         self.sumPath(root, 0)18 19         return self.sum