Skip to content

Commit 419ff7e

Browse files
leetcode:path sum
1 parent bb66853 commit 419ff7e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import com.examplehub.datastructures.binarytree.Node;
4+
5+
public class PathSum {
6+
public static boolean solution1(Node<Integer> node, int sum) {
7+
if (node == null) {
8+
return false;
9+
}
10+
if (node.value == sum && node.left == null && node.right == null) {
11+
return true;
12+
}
13+
return solution1(node.left, sum - node.value) || solution1(node.right, sum - node.value);
14+
}
15+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import com.examplehub.datastructures.binarytree.Node;
4+
import org.junit.jupiter.api.Test;
5+
6+
import static org.junit.jupiter.api.Assertions.assertFalse;
7+
import static org.junit.jupiter.api.Assertions.assertTrue;
8+
9+
class PathSumTest {
10+
@Test
11+
void testSolution1() {
12+
Node<Integer> root = new Node<>(5);
13+
root.left = new Node<>(4);
14+
root.right = new Node<>(8);
15+
root.left.left = new Node<>(11);
16+
root.right.left = new Node<>(13);
17+
root.right.right = new Node<>(4);
18+
root.left.left.left = new Node<>(7);
19+
root.left.left.right = new Node<>(2);
20+
root.right.right.right = new Node<>(1);
21+
22+
assertTrue(PathSum.solution1(root, 22));
23+
assertTrue(PathSum.solution1(root, 26));
24+
assertFalse(PathSum.solution1(root, 100));
25+
}
26+
}

0 commit comments

Comments
 (0)