File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -164,6 +164,54 @@ public:
164
164
165
165
Java:
166
166
167
+ ``` java
168
+ class Solution {
169
+ List<Integer > path = new ArrayList<> ();
170
+ int res = 0 ;
171
+
172
+ public int sumNumbers (TreeNode root ) {
173
+ // 如果节点为0,那么就返回0
174
+ if (root == null ) return 0 ;
175
+ // 首先将根节点放到集合中
176
+ path. add(root. val);
177
+ // 开始递归
178
+ recur(root);
179
+ return res;
180
+ }
181
+
182
+ public void recur (TreeNode root ){
183
+ if (root. left == null && root. right == null ) {
184
+ // 当是叶子节点的时候,开始处理
185
+ res += listToInt(path);
186
+ return ;
187
+ }
188
+
189
+ if (root. left != null ){
190
+ // 注意有回溯
191
+ path. add(root. left. val);
192
+ recur(root. left);
193
+ path. remove(path. size() - 1 );
194
+ }
195
+ if (root. right != null ){
196
+ // 注意有回溯
197
+ path. add(root. right. val);
198
+ recur(root. right);
199
+ path. remove(path. size() - 1 );
200
+ }
201
+ return ;
202
+ }
203
+
204
+ public int listToInt (List<Integer > path ){
205
+ int sum = 0 ;
206
+ for (Integer num: path){
207
+ // sum * 10 表示进位
208
+ sum = sum * 10 + num;
209
+ }
210
+ return sum;
211
+ }
212
+ }
213
+ ```
214
+
167
215
Python:
168
216
``` python3
169
217
class Solution :
You can’t perform that action at this time.
0 commit comments