Skip to content

Commit 3fc3a3c

Browse files
committed
Added solution to find paths with target sum
1 parent 60354ea commit 3fc3a3c

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/main/java/com/eprogrammerz/examples/algorithm/trees/Node.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.LinkedList;
44
import java.util.Queue;
5+
import java.util.Stack;
56

67
public class Node {
78
int data;
@@ -105,6 +106,42 @@ private boolean isSubtree(Node t1, Node t2) {
105106
return isSubtree(t1.left, t2.left) && isSubtree(t1.right, t2.right);
106107
}
107108

109+
/**
110+
* Count path that sums to the target value
111+
*
112+
* @return
113+
*/
114+
public int findPaths(int target) {
115+
Queue<Node> queue = new LinkedList<>();
116+
queue.add(this);
117+
118+
int count = 0;
119+
while (!queue.isEmpty()) {
120+
Node node = queue.poll();
121+
122+
count += findPaths(node, target, 0);
123+
124+
if (node.left != null) queue.add(node.left);
125+
126+
if (node.right != null) queue.add(node.right);
127+
}
128+
return count;
129+
}
130+
131+
private int findPaths(Node node, int target, int sum) {
132+
if (node == null) return 0;
133+
sum += node.data;
134+
135+
int totalPaths = 0;
136+
if (target == sum) {
137+
totalPaths++;
138+
}
139+
totalPaths += findPaths(node.left, target, sum);
140+
totalPaths += findPaths(node.right, target, sum);
141+
142+
return totalPaths;
143+
}
144+
108145
@Override
109146
public String toString() {
110147
return "(" + data + ")";
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.eprogrammerz.examples.algorithm.trees;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class PathWithSum {
8+
@Test
9+
public void testFindPath() {
10+
/**
11+
* 10
12+
* / \
13+
* 7 2
14+
* / \ \
15+
* 3 4 8
16+
* \
17+
* 12
18+
*
19+
*/
20+
21+
Node root = new Node(10);
22+
root.left = new Node(7);
23+
root.right = new Node(2);
24+
root.left.left = new Node(3);
25+
root.left.right = new Node(4);
26+
root.right.right = new Node(8);
27+
root.right.right.right = new Node(12);
28+
29+
assertEquals(3, root.findPaths(20));
30+
}
31+
}

0 commit comments

Comments
 (0)