添加0129求根到叶子节点数字之和 Python3版本

This commit is contained in:
Steve0x2a
2021-08-17 13:59:39 +08:00
committed by GitHub
parent e11fa42c52
commit a648b12e31

View File

@ -165,7 +165,32 @@ public:
Java
Python
```python3
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
res = 0
path = []
def backtrace(root):
nonlocal res
if not root: return # 节点空则返回
path.append(root.val)
if not root.left and not root.right: # 遇到了叶子节点
res += get_sum(path)
if root.left: # 左子树不空
backtrace(root.left)
if root.right: # 右子树不空
backtrace(root.right)
path.pop()
def get_sum(arr):
s = 0
for i in range(len(arr)):
s = s * 10 + arr[i]
return s
backtrace(root)
return res
```
Go
JavaScript