Skip to content

Commit 9a25b74

Browse files
committed
129. 求根到叶子节点数字之和
1 parent ac1d570 commit 9a25b74

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

tree/129_sumNumbers.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
# Definition for a binary tree node.
2+
import collections
3+
4+
25
class TreeNode:
36
def __init__(self, x):
47
self.val = x
@@ -22,3 +25,26 @@ def dfs(root, value):
2225
return dfs(root.left, value) + dfs(root.right, value)
2326

2427
return dfs(root, 0)
28+
29+
def sumNumbers_bfs(self, root: TreeNode) -> int:
30+
if not root:
31+
return 0
32+
33+
q1, q2 = collections.deque(), collections.deque()
34+
q1.append(root)
35+
q2.append(root.val)
36+
37+
ans = 0
38+
while q1:
39+
node = q1.popleft()
40+
num = q2.popleft()
41+
if not node.left and not node.right:
42+
ans += num
43+
else:
44+
if node.left:
45+
q1.append(node.left)
46+
q2.append(num * 10 + node.left.val)
47+
if node.right:
48+
q1.append(node.right)
49+
q2.append(num * 10 + node.right.val)
50+
return ans

0 commit comments

Comments
 (0)