- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSumRootToLeafNum.py
More file actions
Latest commit
36 lines (30 loc) · 843 Bytes
/
Copy pathSumRootToLeafNum.py
File metadata and controls
36 lines (30 loc) · 843 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
'''
Sum Root to Leaf Number
'''
classNode(object):
def__init__(self,val=None,left=None,right=None):
self.val=val
self.left=left
self.right=right
defSumNumbers(root):
returnSumRootToLeaf(root,0)
defSumRootToLeaf(root,total) :
'''
Args: a binary tree containing digits from 0-9 only,
each root to leaf path represent a number
Return: total sum of all root to leaf numbers
For example,
1
2 3
represents as 123, 1->2 represents 12, 1->3 represents 13
return the sum = 12 + 13 = 25
'''
ifrootisNone :
return0
total=total*10+root.val
ifroot.leftisNoneandroot.rightisNone:
returntotal
else :
returnSumRootToLeaf(root.left,total) +SumRootToLeaf(root.right,total)
root=Node(1,Node(2,Node(4)),Node(3))
printSumNumbers(root)