首页 > 其他 > 详细

#Leet Code# Root to leaf

时间:2014-07-16 21:36:47      阅读:298      评论:0      收藏:0      [点我收藏+]

语言: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

#Leet Code# Root to leaf

原文:http://www.cnblogs.com/mess4u/p/3835756.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!