File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
3+
4+ An example is the root-to-leaf path 1->2->3 which represents the number 123.
5+
6+ Find the total sum of all root-to-leaf numbers.
7+
8+ For example,
9+
10+ 1
11+ / \
12+ 2 3
13+ The root-to-leaf path 1->2 represents the number 12.
14+ The root-to-leaf path 1->3 represents the number 13.
15+
16+ Return the sum = 12 + 13 = 25.
17+ '''
18+
19+ # Definition for a binary tree node.
20+ class TreeNode (object ):
21+ def __init__ (self , x ):
22+ self .val = x
23+ self .left = None
24+ self .right = None
25+
26+
27+ class Solution (object ):
28+ def sumNumbers (self , root ):
29+ """
30+ :type root: TreeNode
31+ :rtype: int
32+ """
33+ return self ._sumNumbers (root , 0 )
34+
35+ def _sumNumbers (self , root , s ):
36+ if root is None :
37+ return 0
38+ s = s * 10 + root .val
39+ return sum ([self ._sumNumbers (r , s ) for r in (root .left , root .right )]) or s
40+
41+ if __name__ == "__main__" :
42+ None
You can’t perform that action at this time.
0 commit comments