From a648b12e31822b023501bb60e12403b6ba54095d Mon Sep 17 00:00:00 2001 From: Steve0x2a Date: Tue, 17 Aug 2021 13:59:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00129=E6=B1=82=E6=A0=B9?= =?UTF-8?q?=E5=88=B0=E5=8F=B6=E5=AD=90=E8=8A=82=E7=82=B9=E6=95=B0=E5=AD=97?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20Python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0129.求根到叶子节点数字之和.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index b37270e2..17642793 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -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: