@@ -64,7 +64,7 @@ Therefore, sum = 495 + 491 + 40 = 1026.
6464
6565## 代码
6666
67- * 语言支持:JS,C++
67+ * 语言支持:JS,C++,Python
6868
6969JavaScipt Code:
7070
@@ -131,6 +131,33 @@ private:
131131};
132132```
133133
134+ Python Code:
135+
136+ ```python
137+ # class TreeNode:
138+ # def __init__(self, x):
139+ # self.val = x
140+ # self.left = None
141+ # self.right = None
142+
143+ class Solution:
144+ def sumNumbers(self, root: TreeNode) -> int:
145+
146+ def helper(node, cur_val):
147+ if not node: return 0
148+ next_val = cur_val * 10 + node.val
149+
150+ if not (node.left or node.right):
151+ return next_val
152+
153+ left_val = helper(node.left, next_val)
154+ right_val = helper(node.right, next_val)
155+
156+ return left_val + right_val
157+
158+ return helper(root, 0)
159+ ```
160+
134161## 拓展
135162
136163通常来说,可以利用队列、栈等数据结构将递归算法转为递推算法。
@@ -148,7 +175,12 @@ private:
1481754 . 若右子树非空,则将该值乘以10加上右子树的值,并添加到当前和队列中
1491765 . 若左右子树均为空时,将该节点的当前和加到返回值中
150177
151- ### C++实现
178+ ## 实现
179+
180+ * 语言支持:C++,Python
181+
182+ C++ Code:
183+
152184``` C++
153185class Solution {
154186public:
@@ -171,7 +203,7 @@ public:
171203 if (n->right != nullptr) {
172204 runningSum.push_back(tmp * 10 + n->right->val);
173205 queue.push_back(n->right);
174- }
206+ }
175207 if (n->left == nullptr && n->right == nullptr) {
176208 ret += tmp;
177209 }
@@ -181,9 +213,32 @@ public:
181213 }
182214};
183215```
216+
217+ Python Code:
218+
219+ ```python
220+ class Solution:
221+ def sumNumbers(self, root: TreeNode) -> int:
222+ if not root: return 0
223+ result = 0
224+ node_queue, sum_queue = [root], [root.val]
225+ while node_queue:
226+ for i in node_queue:
227+ cur_node = node_queue.pop(0)
228+ cur_val = sum_queue.pop(0)
229+ if cur_node.left:
230+ node_queue.append(cur_node.left)
231+ sum_queue.append(cur_val * 10 + cur_node.left.val)
232+ if cur_node.right:
233+ node_queue.append(cur_node.right)
234+ sum_queue.append(cur_val * 10 + cur_node.right.val)
235+ if not (cur_node.left or cur_node.right):
236+ result += cur_val
237+ return result
238+ ```
239+
184240## 相关题目
185241
186242- [ sum-of-root-to-leaf-binary-numbers] ( https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ )
187243
188244> 这道题和本题太像了,跟一道题没啥区别
189-
0 commit comments