Skip to content

Commit dff0456

Browse files
update 129
1 parent 76898e3 commit dff0456

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

src/main/java/com/fishercoder/solutions/_129.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,7 @@ public int sumNumbers(TreeNode root) {
1313
}
1414
List<Integer> allNumbers = new ArrayList();
1515
dfs(root, new StringBuilder(), allNumbers);
16-
int sum = 0;
17-
for (int i : allNumbers) {
18-
sum += i;
19-
}
20-
return sum;
16+
return allNumbers.stream().mapToInt(i -> i).sum();
2117
}
2218

2319
private void dfs(TreeNode root, StringBuilder sb, List<Integer> allNumbers) {
@@ -31,6 +27,8 @@ private void dfs(TreeNode root, StringBuilder sb, List<Integer> allNumbers) {
3127
if (root.left == null && root.right == null) {
3228
allNumbers.add(Integer.parseInt(sb.toString()));
3329
}
30+
//this is to delete the last value. since it's guaranteed that the value is between [0,9], so only one char needs to be deleted.
31+
//however if the value is >= 10 then this approach needs to be adjusted
3432
sb.deleteCharAt(sb.length() - 1);
3533
}
3634
}
@@ -47,7 +45,9 @@ private int dfs(TreeNode root, int sum) {
4745
if (root.left == null && root.right == null) {
4846
return sum * 10 + root.val;
4947
}
50-
return dfs(root.left, sum * 10 + root.val) + dfs(root.right, sum * 10 + root.val);
48+
int left = dfs(root.left, sum * 10 + root.val);
49+
int right = dfs(root.right, sum * 10 + root.val);
50+
return left + right;
5151
}
5252
}
5353

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
import com.fishercoder.common.utils.TreeUtils;
5+
import com.fishercoder.solutions._129;
6+
import org.junit.jupiter.api.BeforeEach;
7+
import org.junit.jupiter.api.Test;
8+
9+
import java.util.Arrays;
10+
11+
import static org.junit.jupiter.api.Assertions.assertEquals;
12+
13+
public class _129Test {
14+
private static _129.Solution1 solution1;
15+
private static _129.Solution2 solution2;
16+
17+
@BeforeEach
18+
public void setup() {
19+
solution1 = new _129.Solution1();
20+
solution2 = new _129.Solution2();
21+
}
22+
23+
@Test
24+
public void test1() {
25+
TreeNode root = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3));
26+
assertEquals(25, (solution1.sumNumbers(root)));
27+
assertEquals(25, (solution2.sumNumbers(root)));
28+
}
29+
30+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy