Skip to content

Commit c6c60a3

Browse files
committed
sumNumbers
sumNumbers
1 parent 4728a4d commit c6c60a3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

tree/SumNumbers.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package Algorithms.tree;
2+
3+
import java.util.ArrayList;
4+
5+
/*
6+
*
7+
* Sum Root to Leaf Numbers Total Accepted: 23940 Total Submissions: 80436 My Submissions
8+
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
9+
10+
An example is the root-to-leaf path 1->2->3 which represents the number 123.
11+
12+
Find the total sum of all root-to-leaf numbers.
13+
14+
For example,
15+
16+
1
17+
/ \
18+
2 3
19+
The root-to-leaf path 1->2 represents the number 12.
20+
The root-to-leaf path 1->3 represents the number 13.
21+
22+
Return the sum = 12 + 13 = 25.
23+
* */
24+
25+
public class SumNumbers {
26+
public int sumNumbers(TreeNode root) {
27+
if (root == null) {
28+
return 0;
29+
}
30+
31+
ArrayList<Integer> ret = new ArrayList<Integer>();
32+
33+
// 存储从根节点到当前节点的路径上的数字
34+
ArrayList<Integer> path = new ArrayList<Integer>();
35+
36+
dfs(root, path, ret);
37+
int sum = 0;
38+
for (int n: ret) {
39+
sum += n;
40+
}
41+
42+
return sum;
43+
}
44+
45+
public void dfs(TreeNode root, ArrayList<Integer> path, ArrayList<Integer> ret) {
46+
if (root == null) {
47+
return;
48+
}
49+
50+
path.add(root.val);
51+
52+
if (root.left == null && root.right == null) {
53+
int num = 0;
54+
for (int n: path) {
55+
num = num * 10 + n;
56+
}
57+
ret.add(num);
58+
} else {
59+
// 向左右子树递归
60+
dfs(root.left, path, ret);
61+
dfs(root.right, path, ret);
62+
}
63+
64+
// 一定要记得回溯,也就是说递归不能修改Path本身,否则以上向左右子树分别递归时 path就会被改。
65+
path.remove(path.size() - 1);
66+
}
67+
}

0 commit comments

Comments
 (0)