-
Notifications
You must be signed in to change notification settings - Fork 33
/
Problem_12.java
72 lines (67 loc) · 1.92 KB
/
Problem_12.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Cracking-The-Coding-Interview
* Problem_12.java
*/
package com.deepak.ctci.Ch04_Trees_And_Graphs;
import com.deepak.ctci.Library.TreeNode;
/**
* <br> Problem Statement :
*
* You are given a binary tree in which each node contains
* an integer value (which might be positive or negative).
* Design an algorithm to count the number of paths that
* sum to a given value. The path does not need to start
* at root or end at leaf, but it must go downwards (traveling
* only from parent node to child nodes)
*
* </br>
*
* @author Deepak
*/
public class Problem_12 {
/**
* Method to find the count of paths with sum
*
* @param root
* @param sum
* @return {@link int}
*/
public static int countPathsWithSum(TreeNode<Integer> root, int sum) {
/* If root is null, zero paths available */
if (root == null) {
return 0;
}
/* Count paths with sum starting from root */
int pathsFromRoot = countPathsWithSumFromNode(root, sum, 0);
/* Find paths from left sub tree and right sub tree */
int pathsOnLeft = countPathsWithSum(root.left, sum);
int pathsOnRight = countPathsWithSum(root.right, sum);
/* Return total sum */
return pathsFromRoot + pathsOnLeft + pathsOnRight;
}
/**
* Methods to count paths with sum from a given node
*
* @param node
* @param sum
* @param currentSum
* @return {@link int}
*/
private static int countPathsWithSumFromNode(TreeNode<Integer> node, int sum, int currentSum) {
/* If node is null, no path exists */
if (node == null) {
return 0;
}
/* Update the current sum */
currentSum += node.data;
int totalPaths = 0;
/* If current sum and target sum matches, we found a path */
if (currentSum == sum) {
totalPaths++;
}
/* Find paths for left subtree and right subtree */
totalPaths += countPathsWithSumFromNode(node.left, sum, currentSum);
totalPaths += countPathsWithSumFromNode(node.right, sum, currentSum);
return totalPaths;
}
}