-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0129-sum-root-to-leaf-numbers.py
More file actions
34 lines (26 loc) · 853 Bytes
/
0129-sum-root-to-leaf-numbers.py
File metadata and controls
34 lines (26 loc) · 853 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
# time complexity: O(n)
# space complexity: O(h)
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> List[int]:
sumNode = 0
def traverse(node: Optional[TreeNode], currNum: int):
nonlocal sumNode
if node is None:
return
currNum = currNum * 10 + node.val
if node.left is None and node.right is None:
sumNode += currNum
traverse(node.left, currNum)
traverse(node.right, currNum)
traverse(root, 0)
return sumNode
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(Solution().sumNumbers(root))