File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
src/main/java/com/eprogrammerz/examples/algorithm/trees Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 22
33import java .util .LinkedList ;
44import java .util .Queue ;
5+ import java .util .Stack ;
56
67public 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 + ")" ;
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments