forked from everbird/leetcode-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum-root-to-leaf-numbers.py
More file actions
62 lines (41 loc) · 932 Bytes
/
sum-root-to-leaf-numbers.py
File metadata and controls
62 lines (41 loc) · 932 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):
left = None
right = None
value = -1
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
sum_array = []
stack = []
def bfs(node):
if not node:
return
stack.append(node.value)
if not node.left and not node.right:
_sum = int(''.join(map(str, stack)))
sum_array.append(_sum)
stack.pop()
return
if node.left:
bfs(node.left)
if node.right:
bfs(node.right)
stack.pop()
def leaf_sum(head):
bfs(head)
return sum(sum_array)
def run():
n3 = Node(1)
n2 = Node(6, right=n3)
n1 = Node(3, right=n2)
head = n1
total = leaf_sum(head)
print sum_array
assert total==361, 'Failed, 4!=%s' % total
def main():
run()
if __name__ == '__main__':
main()