mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
129求根节点的叶节点数字之和Java实现
This commit is contained in:
@ -164,6 +164,54 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
List<Integer> path = new ArrayList<>();
|
||||||
|
int res = 0;
|
||||||
|
|
||||||
|
public int sumNumbers(TreeNode root) {
|
||||||
|
// 如果节点为0,那么就返回0
|
||||||
|
if (root == null) return 0;
|
||||||
|
// 首先将根节点放到集合中
|
||||||
|
path.add(root.val);
|
||||||
|
// 开始递归
|
||||||
|
recur(root);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void recur(TreeNode root){
|
||||||
|
if (root.left == null && root.right == null) {
|
||||||
|
// 当是叶子节点的时候,开始处理
|
||||||
|
res += listToInt(path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (root.left != null){
|
||||||
|
// 注意有回溯
|
||||||
|
path.add(root.left.val);
|
||||||
|
recur(root.left);
|
||||||
|
path.remove(path.size() - 1);
|
||||||
|
}
|
||||||
|
if (root.right != null){
|
||||||
|
// 注意有回溯
|
||||||
|
path.add(root.right.val);
|
||||||
|
recur(root.right);
|
||||||
|
path.remove(path.size() - 1);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int listToInt(List<Integer> path){
|
||||||
|
int sum = 0;
|
||||||
|
for (Integer num:path){
|
||||||
|
// sum * 10 表示进位
|
||||||
|
sum = sum * 10 + num;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python3
|
```python3
|
||||||
class Solution:
|
class Solution:
|
||||||
|
Reference in New Issue
Block a user