Skip to content

Commit 7c7bad9

Browse files
committed
completed 129
1 parent 4d82018 commit 7c7bad9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

129 sum root to leaf number

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val: int = val
7+
self.left: Optional[TreeNode] = left
8+
self.right: Optional[TreeNode] = right
9+
10+
11+
class Solution:
12+
def sumNumbers(self, root: Optional[TreeNode]) -> int:
13+
if not root:
14+
return 0
15+
return sum(int(num) for num in sumn(root))
16+
17+
18+
def sumn(node: TreeNode) -> list[str]:
19+
if not (node.left or node.right):
20+
return [str(node.val)]
21+
digit = str(node.val)
22+
left = [digit + num for num in sumn(node.left)] if node.left else []
23+
right = [digit + num for num in sumn(node.right)] if node.right else []
24+
return left + right

0 commit comments

Comments
 (0)