Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc6c60a3

Browse files
committed
sumNumbers
sumNumbers
1 parent4728a4d commitc6c60a3

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+
packageAlgorithms.tree;
2+
3+
importjava.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+
publicclassSumNumbers {
26+
publicintsumNumbers(TreeNoderoot) {
27+
if (root ==null) {
28+
return0;
29+
}
30+
31+
ArrayList<Integer>ret =newArrayList<Integer>();
32+
33+
// 存储从根节点到当前节点的路径上的数字
34+
ArrayList<Integer>path =newArrayList<Integer>();
35+
36+
dfs(root,path,ret);
37+
intsum =0;
38+
for (intn:ret) {
39+
sum +=n;
40+
}
41+
42+
returnsum;
43+
}
44+
45+
publicvoiddfs(TreeNoderoot,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+
intnum =0;
54+
for (intn: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)

[8]ページ先頭

©2009-2025 Movatter.jp