@@ -74,7 +74,7 @@ https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/
74
74
75
75
## 代码
76
76
77
- * 语言支持:JS,C++,Python
77
+ * 语言支持:JS,C++,Python, Go, PHP
78
78
79
79
JavaScipt Code:
80
80
@@ -168,6 +168,79 @@ class Solution:
168
168
return helper(root, 0)
169
169
```
170
170
171
+ Go Code:
172
+
173
+ ``` go
174
+ /* *
175
+ * Definition for a binary tree node.
176
+ * type TreeNode struct {
177
+ * Val int
178
+ * Left *TreeNode
179
+ * Right *TreeNode
180
+ * }
181
+ */
182
+ func sumNumbers (root *TreeNode ) int {
183
+ return helper (root, 0 )
184
+ }
185
+
186
+ func helper (root *TreeNode , cur int ) int {
187
+ if root == nil {
188
+ return 0 // 当前非叶子节点, 不计算
189
+ }
190
+
191
+ next := cur*10 + root.Val
192
+ if root.Left == nil && root.Right == nil {
193
+ return next // 当前为叶子节点, 计算
194
+ }
195
+
196
+ l := helper (root.Left , next)
197
+ r := helper (root.Right , next)
198
+ return l + r
199
+ }
200
+ ```
201
+
202
+ PHP Code:
203
+
204
+ ``` php
205
+ /**
206
+ * Definition for a binary tree node.
207
+ * class TreeNode {
208
+ * public $val = null;
209
+ * public $left = null;
210
+ * public $right = null;
211
+ * function __construct($value) { $this->val = $value; }
212
+ * }
213
+ */
214
+ class Solution
215
+ {
216
+
217
+ /**
218
+ * @param TreeNode $root
219
+ * @return Integer
220
+ */
221
+ function sumNumbers($root)
222
+ {
223
+ return (new Solution())->helper($root, 0);
224
+ }
225
+
226
+ /**
227
+ * @param TreeNode $root
228
+ * @param int $cur
229
+ * @return int
230
+ */
231
+ function helper($root, $cur)
232
+ {
233
+ if (!$root) return 0; // 当前不是叶子节点
234
+ $next = $cur * 10 + $root->val;
235
+ if (!$root->left && !$root->right) return $next; // 当前为叶子节点, 返回叶子节点的值
236
+
237
+ $l = (new Solution())->helper($root->left, $next);
238
+ $r = (new Solution())->helper($root->right, $next);
239
+ return $l + $r;
240
+ }
241
+ }
242
+ ```
243
+
171
244
** 复杂度分析**
172
245
173
246
- 时间复杂度:$O(N)$
0 commit comments