Skip to content

Commit a81bbd4

Browse files
committed
10.6 done and test fixed
1 parent fd4bbaa commit a81bbd4

3 files changed

Lines changed: 17 additions & 6 deletions

File tree

binarytrees/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
- [x] 10.3 ComputeLowestCommonAncestor
66
- [x] 10.4 ComputeLCAWithParent
77
- [x] 10.5 SumRootToLeaf
8-
- [ ] 10.6 FindRootToLeafSum
8+
- [x] 10.6 FindRootToLeafSum
99
- [ ] 10.7 InorderIterative
1010
- [ ] 10.8 PreorderIterative
1111
- [ ] 10.9 ComputeKthNodeInorder

binarytrees/src/main/java/FindRootToLeafSum.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,20 @@ public class FindRootToLeafSum {
44
10.6
55
*/
66

7-
public static boolean hasPathSum(BinaryTree<Integer> tree, int targetSum) {
7+
public static boolean hasPathSum(BinaryTree<Integer> tree, Integer targetSum) {
8+
return exists(tree, targetSum, 0);
9+
}
10+
11+
private static boolean exists(BinaryTree<Integer> node, Integer targetSum, Integer count) {
12+
if (node == null)
13+
return false;
14+
15+
int current = node.data + count;
16+
if (node.left == null && node.right == null)
17+
return targetSum.equals(current);
818

9-
return false;
19+
return exists(node.left, targetSum, current) ||
20+
exists(node.right, targetSum, current);
1021
}
1122

1223
}

binarytrees/src/test/java/FindRootToLeafSumTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public class FindRootToLeafSumTest {
1212
public void hasPathSum1() throws Exception {
1313
expected = true;
1414
tree = BinaryTreeUtil.getFullTree();
15-
targetSum = 10;
15+
targetSum = 7;
1616

1717
test(expected, tree, targetSum);
1818
}
@@ -30,7 +30,7 @@ public void hasPathSum2() throws Exception {
3030
public void hasPathSum3() throws Exception {
3131
expected = true;
3232
tree = BinaryTreeUtil.getFigureTenDotOne();
33-
targetSum = 519;
33+
targetSum = 1365;
3434

3535
test(expected, tree, targetSum);
3636
}
@@ -39,7 +39,7 @@ public void hasPathSum3() throws Exception {
3939
public void hasPathSum4() throws Exception {
4040
expected = false;
4141
tree = BinaryTreeUtil.getFigureTenDotOne();
42-
targetSum = 591;
42+
targetSum = 724;
4343

4444
test(expected, tree, targetSum);
4545
}

0 commit comments

Comments
 (0)