Skip to content

Commit 41f2652

Browse files
committed
�129求根节点的叶节点数字之和Java实现
1 parent cd7ef34 commit 41f2652

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

problems/0129.求根到叶子节点数字之和.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,54 @@ public:
164164

165165
Java:
166166

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+
167215
Python:
168216
```python3
169217
class Solution:

0 commit comments

Comments
 (0)